首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何自动标尺y轴的条形图在材料库?

如何自动标尺y轴的条形图在材料库?
EN

Stack Overflow用户
提问于 2020-08-21 14:21:53
回答 1查看 690关注 0票数 0

我需要用matplotlib自动缩放条形图上的y轴,以显示值的微小差异。它需要自动标度而不是有固定限制的原因是,值将根据用户输入的内容而改变。我试过yscale log,但这对负值不起作用。我尝试过symlog,但是图表保持不变。这是我目前的代码:

代码语言:javascript
运行
AI代码解释
复制
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = range(700, 710, 1)
fig, ax = plt.subplots()
ax.bar(x, y)
plt.show()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-21 15:15:58

  • 绘图是自动缩放提供给API的全部数据的。条形图的
  • (显示条形图值差异的最佳选项)可能是为竖直条设置ylim或为水平条设置xlim

负数据

代码语言:javascript
运行
AI代码解释
复制
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = range(-700, -750, -5)
fig, ax = plt.subplots(figsize=(7, 5))
ax.bar(x, y)
plt.ylim(min(y), max(y))

正数据

代码语言:javascript
运行
AI代码解释
复制
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = range(700, 750, 5)
fig, ax = plt.subplots(figsize=(7, 5))
ax.bar(x, y)
plt.ylim(min(y), max(y))

混合数据

如果数据具有广泛的正值和负值,那么

  • 可能不是一个好的选择,正如您已经指出的,symlog无助于解决这个问题。最佳选择可能是绘制正负数据separately.

创建掩码的

  • 不适用于列表,因此将列表转换为numpy数组。

代码语言:javascript
运行
AI代码解释
复制
import numpy as np

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [700, -700, 710, -710, 720, -720, 730, -730, 740, -740]

x = np.array(x)
y = np.array(y)

mask = y >= 0  # positive mask

pos_y = y[mask]  # get the positive values
neg_y = y[~mask]  # get the negative values; ~ is not

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7, 5))
ax1.bar(x[mask], pos_y)  # also mask x to plot the bar at the correct x-tick
ax1.set_title('Positive Values')
ax1.set_ylim(min(pos_y), max(pos_y))
ax1.set_xticks(range(0, 12))  # buffer the number of x-ticks, so the x-ticks of the two plots align.

ax2.bar(x[~mask], neg_y)
ax2.set_title('Negative Values')
ax2.set_ylim(min(neg_y), max(neg_y))
ax2.set_xticks(range(0, 12))

plt.tight_layout()  # better spacing between the two plots

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63530746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档