pandas 如何在具有不同 Y 轴的同一个 seaborn 图中很好地制作条形图和线图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37930693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make a barplot and a lineplot in the same seaborn plot with different Y axes nicely?
提问by Martín Fixman
I have two different sets of data with a common index, and I want to represent the first one as a barplot and the second one as a lineplot in the same graph. My current approach is similar to the following.
我有两组具有共同索引的不同数据集,我想在同一图中将第一组表示为条形图,将第二组表示为线图。我目前的方法类似于以下内容。
ax = pt.a.plot(alpha = .75, kind = 'bar')
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(), pt.b.values, alpha = .75, color = 'r')
And the result is similar to this
结果与此类似
This image is really nice and almostright. My only problem is that ax.twinx()
seems to create a new canvas on top of the previous one, and the white lines are clearly seen on top of the barplot.
这张图片非常好,几乎是正确的。我唯一的问题是ax.twinx()
似乎在前一个画布的顶部创建了一个新画布,并且在条形图的顶部可以清楚地看到白线。
Is there any way to plot this without including the white lines?
有没有办法在不包括白线的情况下绘制它?
采纳答案by Serenity
You have to remove grid lines of the second axis. Add to the code ax2.grid(False)
. However y-ticks of the second axis will be not align to y-ticks of the first y-axis, like here:
您必须删除第二个轴的网格线。添加到代码中 ax2.grid(False)
。但是,第二个轴的 y-ticks 不会与第一个 y 轴的 y-ticks 对齐,如下所示:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(pd.Series(np.random.uniform(0,1,size=10)), color='g')
ax2 = ax1.twinx()
ax2.plot(pd.Series(np.random.uniform(0,17,size=10)), color='r')
ax2.grid(False)
plt.show()