Pandas条形图错误B

2024-06-01 07:44:17 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在绘制熊猫数据帧的错误条。现在错误栏的顶部有一个奇怪的箭头,但我想要的是一条水平线。例如,这样的图形: 但现在我的错误栏以箭头而不是水平线结束。

下面是我用来生成它的代码:

plot = meansum.plot(kind='bar',yerr=stdsum,colormap='OrRd_r',edgecolor='black',grid=False,figsize=(8,2),ax=ax,position=0.45,error_kw=dict(ecolor='black',elinewidth=0.5,lolims=True,marker='o'),width=0.8)

所以我应该改变什么使错误成为我想要的。谢谢。


Tags: 数据代码图形plot错误绘制bar箭头
2条回答

使用matplotlib中的plt.errorbar更容易,因为它返回几个对象,包括包含要更改的标记的caplines(当lolims设置为True时自动使用的箭头,请参阅docs)。

使用pandas,只需在plot的子代中挖掘正确的行并更改其标记:

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({"val":[1,2,3,4],"error":[.4,.3,.6,.9]})
meansum = df["val"]
stdsum = df["error"]

plot = meansum.plot(kind='bar',yerr=stdsum,colormap='OrRd_r',edgecolor='black',grid=False,figsize=8,2),ax=ax,position=0.45,error_kw=dict(ecolor='black',elinewidth=0.5, lolims=True),width=0.8)
for ch in plot.get_children():
    if str(ch).startswith('Line2D'): # this is silly, but it appears that the first Line in the children are the caplines...
        ch.set_marker('_')
        ch.set_markersize(10) # to change its size
        break
plt.show()

结果如下: Resulting graph

只要不设置lolim = True就可以了,示例数据如下:

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({"val":[1,2,3,4],"error":[.4,.3,.6,.9]})
meansum = df["val"]
stdsum = df["error"]

plot = meansum.plot(kind='bar',yerr=stdsum,colormap='OrRd_r',edgecolor='black',grid=False,figsize=(8,2),ax=ax,position=0.45,error_kw=dict(ecolor='black',elinewidth=0.5),width=0.8)
plt.show()

相关问题 更多 >