用seaborn绘制堆积柱状图和折线图到一张画布上,堆积柱状图和折线图分别使用不同的Y轴,都有图例
时间: 2024-05-14 20:14:53 浏览: 97
以下是一个示例代码,其中使用了Seaborn中的`barplot`和`lineplot`绘制堆积柱状图和折线图,使用了`twinx()`函数创建另一个Y轴,并使用`legend()`函数添加图例:
```python
import seaborn as sns
import matplotlib.pyplot as plt
# 创建数据
tips = sns.load_dataset('tips')
grouped = tips.groupby(['day', 'time']).agg({'total_bill': 'mean', 'tip': 'mean'}).reset_index()
# 创建画布和子图
fig, ax1 = plt.subplots(figsize=(10,6))
# 绘制堆积柱状图
sns.barplot(data=grouped, x='day', y='total_bill', hue='time', ax=ax1)
# 创建第二个Y轴并绘制折线图
ax2 = ax1.twinx()
sns.lineplot(data=grouped, x='day', y='tip', hue='time', ax=ax2, sort=False)
# 添加图例
ax1.legend(loc='upper left', bbox_to_anchor=(1,1))
ax2.legend(loc='upper right', bbox_to_anchor=(1,0.9))
# 设置坐标轴标签和标题
ax1.set_xlabel('Day')
ax1.set_ylabel('Total Bill')
ax2.set_ylabel('Tip')
plt.title('Total Bill and Tip by Day and Time')
plt.show()
```
这将生成以下图表:

阅读全文
相关推荐


















