我正在使用Pandas和Matplotlib来创建一些情节。我想要带有误差线的线图。我目前使用的代码如下所示
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame(index=[10,100,1000,10000], columns=['A', 'B', 'C', 'D', 'E', 'F'], data=np.random.rand(4,6))
df_yerr = pd.DataFrame(index=[10,100,1000,10000], columns=['A', 'B', 'C', 'D', 'E', 'F'], data=np.random.rand(4,6))
fig, ax = plt.subplots()
df.plot(yerr=df_yerr, ax=ax, fmt="o-", capsize=5)
ax.set_xscale("log")
plt.show()
使用此代码,我在一个图上得到6行(这就是我想要的)。但是,误差条完全重叠,使得绘图难以阅读。
有没有办法可以稍微移动x轴上每个点的位置,以便误差条不再重叠?
以下是截图:
答案 0 :(得分:3)
实现你想要的东西的一种方法是用手绘制错误条,但它既不是直接的,也不是比你原来的好看。基本上,你要做的是让pandas
生成线图,然后遍历数据框列并为每个列做一个pyplot errorbar
图,这样,索引会略微向侧面移动(在你的例如,在x轴上具有对数标度,这将是一个因子的偏移。在误差线图中,标记大小设置为零:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
colors = ['red','blue','green','yellow','purple','black']
df = pd.DataFrame(index=[10,100,1000,10000], columns=['A', 'B', 'C', 'D', 'E', 'F'], data=np.random.rand(4,6))
df_yerr = pd.DataFrame(index=[10,100,1000,10000], columns=['A', 'B', 'C', 'D', 'E', 'F'], data=np.random.rand(4,6))
fig, ax = plt.subplots()
df.plot(ax=ax, marker="o",color=colors)
index = df.index
rows = len(index)
columns = len(df.columns)
factor = 0.95
for column,color in zip(range(columns),colors):
y = df.values[:,column]
yerr = df_yerr.values[:,column]
ax.errorbar(
df.index*factor, y, yerr=yerr, markersize=0, capsize=5,color=color,
zorder = 10,
)
factor *= 1.02
ax.set_xscale("log")
plt.show()
正如我所说,结果并不漂亮:
<强>更新强>
在我看来,条形图会提供更多信息:
fig2,ax2 = plt.subplots()
df.plot(kind='bar',yerr=df_yerr, ax=ax2)
plt.show()
答案 1 :(得分:0)