简体   繁体   English

如何在具有不同 Y 轴的同一个 seaborn 图中很好地制作条形图和线图?

[英]How can I make a barplot and a lineplot in the same seaborn plot with different Y axes nicely?

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 almost right.这张图片非常好,几乎是正确的。 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?有没有办法在不包括白线的情况下绘制它?

You can use twinx() method along with seaborn to create a seperate y-axis, one for the lineplot and the other for the barplot.您可以将twinx()方法与 seaborn 一起使用来创建一个单独的 y 轴,一个用于线图,另一个用于条形图。 To control the style of the plot (default style of seaborn is darkgrid), you can use set_style method and specify the preferred theme.要控制绘图的样式(seaborn 的默认样式为darkgrid),您可以使用 set_style 方法并指定首选主题。 If you set style=None it resets to white background without the gridlines.如果您设置style=None它会重置为没有网格线的白色背景。 You can also try whitegrid .您也可以尝试whitegrid If you want to further customize the gridlines, you can do it on the axis level using the ax2.grid(False) .如果要进一步自定义网格线,可以使用ax2.grid(False)在轴级别上进行。

import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns

matplotlib.rc_file_defaults()
ax1 = sns.set_style(style=None, rc=None )

fig, ax1 = plt.subplots(figsize=(12,6))

sns.lineplot(data = df['y_var_1'], marker='o', sort = False, ax=ax1)
ax2 = ax1.twinx()

sns.barplot(data = df, x='x_var', y='y_var_2', alpha=0.5, ax=ax2)

共享相同 x 轴和不同 y 轴的条形图和线图 seaborn 示例

You have to remove grid lines of the second axis.您必须删除第二个轴的网格线。 Add to the code ax2.grid(False) .添加到代码ax2.grid(False) However y-ticks of the second axis will be not align to y-ticks of the first y-axis, like here:但是,第二个轴的 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()

在此处输入图片说明

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

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