我有类似于this question的问题;我试图在Seaborn中合并三个图,但y轴上的标签与条形图不对齐。
我的代码(现在是一个工作的复制粘贴示例):
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
### Generate example data
np.random.seed(123)
year = [2018, 2019, 2020, 2021]
task = [x + 2 for x in range(18)]
student = [x for x in range(200)]
amount = [x + 10 for x in range(90)]
violation = [letter for letter in "thisisjustsampletextforlabels"] # one letter labels
df_example = pd.DataFrame({
# some ways to create random data
'year':np.random.choice(year,500),
'task':np.random.choice(task,500),
'violation':np.random.choice(violation, 500),
'amount':np.random.choice(amount, 500),
'student':np.random.choice(student, 500)
})
### My code
temp = df_example.groupby(["violation"])["amount"].sum().sort_values(ascending = False).reset_index()
total_violations = temp["amount"].sum()
sns.set(font_scale = 1.2)
f, axs = plt.subplots(1,3,
figsize=(5,5),
sharey="row",
gridspec_kw=dict(width_ratios=[3,1.5,5]))
# Plot frequency
df1 = df_example.groupby(["year","violation"])["amount"].sum().sort_values(ascending = False).reset_index()
frequency = sns.barplot(data = df1, y = "violation", x = "amount", log = True, ax=axs[0])
# Plot percent
df2 = df_example.groupby(["violation"])["amount"].sum().sort_values(ascending = False).reset_index()
total_violations = df2["amount"].sum()
percent = sns.barplot(x='amount', y='violation', estimator=lambda x: sum(x) / total_violations * 100, data=df2, ax=axs[1])
# Pivot table and plot heatmap
df_heatmap = df_example.groupby(["violation", "task"])["amount"].sum().sort_values(ascending = False).reset_index()
df_heatmap_pivot = df_heatmap.pivot("violation", "task", "amount")
df_heatmap_pivot = df_heatmap_pivot.reindex(index=df_heatmap["violation"].unique())
heatmap = sns.heatmap(df_heatmap_pivot, fmt = "d", cmap="Greys", norm=LogNorm(), ax=axs[2])
plt.subplots_adjust(top=1)
axs[2].set_facecolor('xkcd:white')
axs[2].set(ylabel="",xlabel="Task")
axs[0].set_xlabel('Total amount of violations per year')
axs[1].set_xlabel('Percent (%)')
axs[1].set_ylabel('')
axs[0].set_ylabel('Violation')
结果可以在这里看到:
y-标签根据我的最后一个图,热图对齐。但是,条形图中的条形在顶部剪裁,并且未与标签对齐。我只需要轻推一下酒吧里的酒吧--但怎么做呢?我一直在看文档,但到目前为止我觉得很不清楚。
1条答案
按热度按时间vwkv1x7d1#
violations
,其中包含要绘制的聚合数据。从违规金额总和开始,然后添加一个新的百分比列。这将确保两个条形图具有相同的y轴。df_heatmap_pivot
,请先使用.pivot_table
,然后使用violations.violation
重新索引,而不是使用.groupby
,然后使用violations.violation
重新索引。*在
python 3.10
、pandas 1.4.3
、matplotlib 3.5.1
、seaborn 0.11.2
中测试DataFrame和导入
绘图
sharey='row'
会导致对齐问题。使用sharey=False
,从axs[1]
和axs[2]
中删除yticklabels
,使用axs[1 or 2].set_yticks([])
。heatmap
的ylim
与barplot
的ylim
不同。因此,heatmap
被移位。axs[0]
和axs[1]
是(15.5, -0.5)
,axs[2]
是(16.0, 0.0)
。.bar_label
的其他详细信息和示例,请参见How to add value labels on a bar chart。axs
的yticklabels是否对齐。DataFrame视图
df_example.head()
violations
df_heatmap_pivot