[英]Two seaborn plots with different scales displayed on same plot but bars overlap
I am trying to include 2 seaborn countplots with different scales on the same plot but the bars display as different widths and overlap as shown below.我试图在同一 plot 上包含 2 个具有不同比例的 seaborn 计数图,但条形显示为不同的宽度并重叠,如下所示。 Any idea how to get around this?知道如何解决这个问题吗?
Setting dodge=False, doesn't work as the bars appear on top of each other.设置 dodge=False 不起作用,因为条形显示在彼此之上。
The main problem of the approach in the question, is that the first countplot
doesn't take hue
into account.问题中方法的主要问题是第一个countplot
没有考虑hue
。 The second countplot
won't magically move the bars of the first.第二个countplot
不会神奇地移动第一个计数图。 An additional categorical column could be added, only taking on the 'weekend' value.可以添加一个额外的分类列,仅采用“周末”值。 Note that the column should be explicitly made categorical with two values, even if only one value is really used.请注意,即使仅实际使用了一个值,该列也应明确地使用两个值进行分类。
Things can be simplified a lot, just starting from the original dataframe, which supposedly already has a column 'is_weeked'
.事情可以简化很多,从原来的 dataframe 开始,据说它已经有一个列'is_weeked'
。 Creating the twinx
ax beforehand allows to write a loop (so writing the call to sns.countplot()
only once, with parameters).预先创建twinx
ax 允许编写一个循环(因此只编写一次对sns.countplot()
的调用,并带有参数)。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
sns.set_style('dark')
# create some demo data
data = pd.DataFrame({'ride_hod': np.random.normal(13, 3, 1000).astype(int) % 24,
'is_weekend': np.random.choice(['weekday', 'weekend'], 1000, p=[5 / 7, 2 / 7])})
# now, make 'is_weekend' a categorical column (not just strings)
data['is_weekend'] = pd.Categorical(data['is_weekend'], ['weekday', 'weekend'])
fig, ax1 = plt.subplots(figsize=(16, 6))
ax2 = ax1.twinx()
for ax, category in zip((ax1, ax2), data['is_weekend'].cat.categories):
sns.countplot(data=data[data['is_weekend'] == category], x='ride_hod', hue='is_weekend', palette='Blues', ax=ax)
ax.set_ylabel(f'Count ({category})')
ax1.legend_.remove() # both axes got a legend, remove one
ax1.set_xlabel('Hour of Day')
plt.tight_layout()
plt.show()
use plt.xticks(['put the label by hand in your x label'])使用 plt.xticks(['将 label 手动放入您的 x 标签'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.