【问题标题】:Matplotlib Dynamic Y-Axis Based on Minimum in ListMatplotlib 动态 Y 轴基于列表中的最小值
【发布时间】:2018-10-04 17:44:28
【问题描述】:

我已将特定点的网格温度数据拉入列表,并将其绘制在条形图上,如下所示:

这个网格数据集中的温度不可避免地会降至 0 度以下,我希望缩放 Y 轴,以便具有正值和负值的混合条都将上升到图像的顶部。

我查看了找到here 的示例代码,但据我所知,此代码假定数组中的所有值都是负数,而我正在使用的数据集不会有。

生成如下图的代码(不包括初始列表的构造)如下:

objects = (''+ mon0 +' '+ date0 +'', ''+ mon1 +' '+ date1 +'', ''+ mon2 +' '+ date2 +'', ''+ mon3 +' '+ date3 +'', ''+ mon4 +' '+ date4 +'', ''+ mon5 +' '+ date5 +'', ''+ mon6 +' '+ date6 +'', ''+ mon7 +' '+ date7 +'', ''+ mon8 +' '+ date8 +'', ''+ mon9 +' '+ date9 +'', ''+ mon10 +' '+ date10 +'')
y_pos = np.arange(len(objects))

fig, ax = plt.subplots(figsize=(14,8))

bar_width = 0.40

rects = plt.bar(y_pos, btv_list, bar_width, color='#cc0000', edgecolor='black')
plt.xticks(y_pos, objects)
plt.ylabel('Temperature (°F)')
plt.xticks(y_pos, objects)

for rect in rects:
    y_value = rect.get_height()
    x_value = rect.get_x() + rect.get_width() / 2
    space = 3
    va = 'bottom'
    label = y_value
    plttxt = plt.annotate(label, (x_value, y_value), xytext=(0, space), textcoords="offset points", ha='center', va=va)
    plttxt.set_fontsize(14)
    plttxt.set_weight('semibold')

fig.tight_layout()

【问题讨论】:

  • “具有正值和负值的条形组合都将上升到图像的顶部。”...您能否进一步解释一下,或者在您的问题中显示一些示例输出图?
  • 当然,我为这个脚本提供了一个随机列表,其中包含正值和负值。结果(参见此处的图片:imgur.com/hPjcXYF)在列表中具有负数,从 y 轴上的“0”下降。我的目标是让图表上的所有条形图从列表中的最小值开始上升,在本例中恰好是 -8。

标签: python-3.x matplotlib plot bar-chart


【解决方案1】:

这是你想要得到的吗?

h = np.random.normal(size=(10,))
min_val = min(h)

plt.figure()
rects = plt.bar(x=range(10),height=h-min_val, bottom=min_val)
plt.axhline(0.,ls='--', lw=1, color='grey', zorder=-1)

for rect in rects:
    y_value = rect.get_height()+min_val
    x_value = rect.get_x() + rect.get_width() / 2
    space = 3
    va = 'bottom'
    label = '{:.2f}'.format(y_value)
    plttxt = plt.annotate(label, (x_value, y_value), xytext=(0, space), textcoords="offset points", ha='center', va=va)
    plttxt.set_fontsize(8)
    plttxt.set_weight('semibold')

【讨论】:

  • 这正是我要找的,非常感谢您解决了这个问题!另一个问题,如果我希望数据集中的最小值显示一个条形(尽管在另一个日期的范围内很小),我会从 'bottom=min_val' 中减去一个特定数字吗?
  • 我会使用 np.floor 向下舍入 min_val
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多