python - 线图中的非重叠误差线

标签 python matplotlib plot

我正在使用 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 轴上每个点的位置,使误差条不再重叠?

截图如下:

enter image description here

最佳答案

实现您想要的效果的一种方法是“手动”绘制误差条,但它既不直接,也不比您的原始图好看得多。基本上,您要做的是让 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()

正如我所说,结果并不理想:

result of the code above

更新

在我看来,条形图会提供更多信息:

fig2,ax2 = plt.subplots()
df.plot(kind='bar',yerr=df_yerr, ax=ax2)
plt.show()

result of second piece of code

关于python - 线图中的非重叠误差线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47810149/

相关文章:

python - Linux Mint 上 Shady 中的 LoadPage 非常慢

python - 将 pandas 数据帧转换为位图的更有效方法是什么?

python pandas 重新索引删除 0.0 处的数据

python - Matplotlib 散点图;颜色作为第三个变量的函数

python - 在 Bokeh 中在线性和对数刻度之间切换

python - 如何将多个函数应用于 numpy 数组?

python 属性错误?

python - 使用 `.rstrip()` 和 `.strip() to remove newline `\n`

python - 设置seaborn/matplotlib始终使用edgecolor ='k'参数

python - matplotlib 中带垂直线的图例