使用子图Matplotlib绘制水平线

时间:2018-05-19 03:42:54

标签: python pandas matplotlib data-visualization

我看了下面的帖子并且它有所帮助,但我想知道是否有人以稍微不同的方式尝试过它。

Plotting a horizontal line on multiple subplots in python using pyplot

以下是数据的样子,以便您可以测试(如有必要)= ctr_df

数据的片段可以在下面找到:

Date        LAL_3%      Core        Page_1      Homepage
4/06/2017   0.288142    0.947993    1.174094    0.26622
11/06/2017  0.270052    0.919648    0.615855    0.206031
18/06/2017  0.260225    0.941274    0.550324    0.230775
25/06/2017  0.345208    0.867322    0.373997    0.205385
2/07/2017   0.318578    1.687208    0.420367    0.235314
9/07/2017   0.45653     1.227451    0.71128     0.455536
16/07/2017  0.543492    1.086996    0.415289    0.44763
23/07/2017  0.503581    1.010364    0.642291    0.317182
30/07/2017  0.373479    0.918334    0.580428    0.282783

我的代码如下:

ctr_df.plot(kind='bar', sharey=False, sharex=True, subplots=True, 
                                    legend=True, width=0.8, layout=(2,2), fontsize=12, grid=True, figsize=(20,12), colormap='Dark2')

plt.axhline(0.3, color='k', linestyle='--')
plt.tight_layout()
plt.show()

这将完全返回我想要的内容(按周,按周划分的各个子图),然而,axhline仅出现在最后图上,而不是全部出现。

这可以用我的方法完成吗?我找不到任何可以建议的东西。如果使用这种方法无法做到这一点,那很好,我可以使用上面的线程来帮助修改我的代码。

由于

1 个答案:

答案 0 :(得分:1)

您使用pandas绘图功能,它们的构造相当于完全matplotlib支持。 Afaik,没有办法直接在所有子图中构建水平线。所以回到matplotlib:

from matplotlib import pyplot as plt
import pandas as pd

ctr_df = pd.read_csv("test.csv", delim_whitespace = True,index_col = "Date")
#plot and retrieve axes
axes = ctr_df.plot(kind='bar', sharey=False, sharex=True, subplots=True, 
                                    legend=True, width=0.8, layout=(3,2), fontsize=12, grid=True, figsize=(20,12), colormap='Dark2')
#plot horizontal line in each subplot 
for ax in axes.flatten():
    ax.axhline(0.3, color='k', linestyle='--')
plt.tight_layout()
plt.show()

输出:

enter image description here