[英]Python (matplotlib): how to flip negative bars from upside down to upright in a bar chart
多亏了堆栈溢出和网络上的许多资源,我已经能够使用 matplotlib 创建一个看起来与此类似的图形(这是一个谷歌图像,而不是我的图形)。
现在,我想知道是否有可能让所有的杆都处于直立位置。 因为图形表示的主要目的是在视觉上比较每个组的不同值,但是在某些组颠倒时进行比较在视觉上不吸引人或不方便。
请问如何将负条从倒置翻转到直立位置,以便我的图形看起来像这样?
此外,我有一个制表符分隔的表格,看起来像这样。
Students Grade Eat Sleep Score Label
Ali A -0.5 0.09 2.1 M
Ryan B 0.01 -1.1 -0.08 C
Ben C 0.76 7.5 -0.0001 M
Eyr A 0.5 0.9 -0.087 M
Tify A -0.09 -0.08 0.987 M
Nola B -0.5 0.03 1.18 M
West C 1.2 1.3 -0.76 C
Nile C 0.2 0.07 -1.09 C
我创建了一个 Pandas 数据框,并且能够通过调用从表中绘制特定行:
l1 = df[(df['Grade'] == 'A') & (df['Label'] == 'M')]
我有一个非常大的数据,我想在一张图中包含更多信息以节省空间。 如何在一张图中显示多个信息,例如其中 Grade = A、Grade = C 和 label = M。标签 = M。
小演示:
示例 DF:
In [71]: df
Out[71]:
A
0 100
1 -20
2 130
3 200
4 -80
In [72]: df['A'].plot.bar(grid=True)
Out[72]: <matplotlib.axes._subplots.AxesSubplot at 0xdff9198>
解决方案:
In [75]: ax = df.assign(X=df['A'] + abs(df['A'].min()))['X'].plot.bar(grid=True)
中间结果:
In [76]: new = [int(l.get_text()) + df['A'].min() if l.get_text().isdigit() else l.get_text() for l in ax.get_yticklabels()]
In [77]: ax.set_yticklabels(new)
Out[77]:
[<matplotlib.text.Text at 0xdfa6a20>,
<matplotlib.text.Text at 0xd11cfd0>,
<matplotlib.text.Text at 0xe25c240>,
<matplotlib.text.Text at 0xe25cdd8>,
<matplotlib.text.Text at 0xe269630>,
<matplotlib.text.Text at 0xe269e48>,
<matplotlib.text.Text at 0xd06b198>]
“修复”y-ticks标签后:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.