两个具有不同比例的 seaborn 图显示在同一图上但条形重叠
Two seaborn plots with different scales displayed on same plot but bars overlap
我正在尝试在同一图上包含 2 个不同比例的 seaborn 计数图,但条形图显示为不同的宽度和重叠,如下所示。知道如何解决这个问题吗?
设置 dodge=False 无效,因为条会出现在彼此之上。
使用plt.xticks(['put the label by hand in your x label'])
问题中方法的主要问题是第一个 countplot
没有考虑 hue
。第二个 countplot
不会神奇地移动第一个的条。可以添加一个额外的分类列,仅采用 'weekend' 值。请注意,即使实际上只使用了一个值,也应将列显式分类为具有两个值。
事情可以简化很多,只是从原始数据框开始,据说它已经有一个列 'is_weeked'
。预先创建 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()
我正在尝试在同一图上包含 2 个不同比例的 seaborn 计数图,但条形图显示为不同的宽度和重叠,如下所示。知道如何解决这个问题吗?
设置 dodge=False 无效,因为条会出现在彼此之上。
使用plt.xticks(['put the label by hand in your x label'])
问题中方法的主要问题是第一个 countplot
没有考虑 hue
。第二个 countplot
不会神奇地移动第一个的条。可以添加一个额外的分类列,仅采用 'weekend' 值。请注意,即使实际上只使用了一个值,也应将列显式分类为具有两个值。
事情可以简化很多,只是从原始数据框开始,据说它已经有一个列 'is_weeked'
。预先创建 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()