【问题标题】:Matplotlib Ribbon Plot (fill_between) with a Categorical X-Axis带有分类 X 轴的 Matplotlib 功能区图 (fill_between)
【发布时间】:2018-09-18 17:19:47
【问题描述】:

我有一个组的平均值和标准差,我想创建一个ribbon plot,其中包含平均值和标准差的阴影,但是我有分类 x_axis 列。似乎有一个自动排序功能,可以把所有东西都扔掉。

## Environmental Variables
x_axis = ['Hematite','Illmenite','Goethite','Magnetite','Quartz','Gibbsite','1:1 Clay','Maghemite','Carbonate Minerals','Plagioclase','2:1 Clays','Dolomite','Pyroxene','Calcite','Olivine','Glass']

negative_means = numpy.array([0.14335727,0.05707763,-0.25710322,-0.31085691,0.45552229,0.0092398,0.33358032,-0.31261271,-0.34325373,-0.32826959,-0.22494553,-0.13867505,0.42883104,0.52948655, -0.13867505,0.52948655])

negative_std = numpy.array([0.9218578779912541,1.0417523903222377,0.7225001946958459,0.6634664468936872,1.8400873597252276,1.2279905419059247,1.3735242455660657,0.721879847038041,0.5543207488394122,0.7817647212788771,0.0,0.0,2.088217480513372,2.2160413265187904,0.0,2.216041326518791])


fig, ax = plt.subplots(1)

ax.plot(negative_means, lw=2, label='mean population 1', color='blue')
plt.fill_between(x_axis, negative_means+negative_std, negative_means-negative_std, facecolor='blue', alpha=0.5)

## Set x labels
ax.set_xticklabels(x_axis)
x_max = int(max(plt.xticks()[0]))
# manually set  xtick labels
plt.xticks(range(0, x_max + 1), x_axis, rotation=45) 

结果图如下所示:

如何用分类 x_axis 制定我的情节,使其看起来类似于下面的问题。

Plot yerr/xerr as shaded region rather than error bars

当我将 x_axis 添加到 ax.plot 函数时,会生成结果图:

【问题讨论】:

  • 我猜你忘记将 x 参数提供给 plot、ax.plot(x_axis, negative_means)。然后你负责自己对值进行排序,matplotlib 将简单地按照给定的顺序绘制它们。
  • 嗨@ImportanceOfBeingErnest,感谢您指出这一点。当我添加 x_axis 作为参数时,绘图中的线也会倾斜。我认为我使用 set_xticklabels 处理的相同自动排序正在发生在 fill_between 信息上,我不知道如何更正。
  • 抱歉,您似乎使用的是旧版本的 matplotlib。你能简单地更新到 2.2.2 或 2.2.3 吗?
  • 成功了!!哇!谢谢@ImportanceOfBeingErnest!
  • 优点是您现在可以完全省略“设置 x 标签”部分,因为 matplotlib 会自动为您标记类别。

标签: python matplotlib plot graph linegraph


【解决方案1】:

我刚刚使用 range 更改了 fill_between 的 x 参数,它指定了分类变量的 x 值。在你的代码中休息一切都很好。根据官方文档here,x 值应该是定义曲线的 cx 坐标。根据上面@ImportanceOfBeingErnest 的评论,您可以坚持在绘图时不通过x_axis,这不是最好的方法

plt.fill_between(range(len(x_axis)), negative_means+negative_std, negative_means-negative_std, facecolor='blue', alpha=0.3)
plt.tight_layout()

输出

【讨论】:

  • 嗨@Bazingaa,谢谢!我同意你的观点,建议传递 x_axis 变量。更新我的 matplotlib 解决了这个问题。
  • 不客气。针对与使用旧版本相关的问题提出您的问题。
猜你喜欢
  • 2014-08-21
  • 1970-01-01
  • 2020-11-17
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
  • 2014-06-02
  • 1970-01-01
相关资源
最近更新 更多