简体   繁体   English

使用子图Matplotlib绘制水平线

[英]Plotting Horizontal Line Using Subplots Matplotlib

I have looked at the following thread and it has helped, but I was wondering if anyone had attempted it in a slightly different way. 我看了下面的线程,它有所帮助,但是我想知道是否有人尝试过稍微不同的方式。

Plotting a horizontal line on multiple subplots in python using pyplot 使用pyplot在python中的多个子图上绘制水平线

Below is what the data looks like so you can test (if necessary) = ctr_df 下面是数据的外观,因此您可以进行测试(如有必要)= ctr_df

Snippet of the data can be found below: 数据片段可以在下面找到:

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

My code is below: 我的代码如下:

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()

This returns exactly what I want (individual subplots by audience, by week), however, the axhline is only appearing on the last plot, not all of them. 这恰好返回了我想要的内容(按观众,每周分别细分),但是,axhline仅出现在最后一个情节中,而不是全部出现。

Can this be done using my approach? 可以使用我的方法来完成吗? I can't find anything to suggest it can. 我找不到任何可以建议的东西。 If this is not possible with this approach, that's fine, I can use the above thread to help revise my code. 如果使用这种方法不可能做到这一点,那可以,我可以使用上述线程来帮助修改我的代码。

Thanks 谢谢

You use pandas plotting functions, which are rather constructed for convenience than full matplotlib support. 您使用的是熊猫绘图功能,其构造是为了方便起见,而不是完整的matplotlib支持。 Afaik, there is no way to directly construct horizontal lines in all subplots. Afaik,无法在所有子图中直接构建水平线。 So back to matplotlib: 回到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()

Output: 输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM