用matplotlib.pyplot绘画水平交错柱状图,用导入的热狗大胃王数据取x轴年份y轴各个年份第一名第二名第三名吃的量
时间: 2024-05-19 15:14:20 浏览: 13
以下是使用matplotlib.pyplot绘制水平交错柱状图的示例代码:
```python
import matplotlib.pyplot as plt
# 导入数据
year = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010]
first = [50, 53, 49, 49, 49, 49, 45, 59, 66, 68]
second = [31, 50, 50, 44, 37, 37, 37, 37, 41, 44]
third = [30, 25, 22, 25, 31, 31, 31, 31, 31, 31]
# 绘制水平交错柱状图
plt.barh(year, first, height=0.5, color='red', align='center')
plt.barh(year, second, height=0.5, color='blue', align='center', left=first)
plt.barh(year, third, height=0.5, color='green', align='center', left=[i+j for i,j in zip(first,second)])
# 设置图例和标签
plt.legend(['First Place', 'Second Place', 'Third Place'], loc='lower right')
plt.xlabel('Hot Dogs Eaten')
plt.ylabel('Year')
plt.title('Nathan\'s Famous Hot Dog Eating Contest Winners (2001-2010)')
# 显示图形
plt.show()
```
这段代码可以生成以下水平交错柱状图:
![hotdog_contest_winners.png](https://i.loli.net/2021/09/13/29wFQh5a3Pc8WbA.png)
其中,红色柱子表示第一名吃的热狗数量,蓝色柱子表示第二名,绿色柱子表示第三名。这里使用`align='center'`参数来让柱子居中对齐,使用`left`参数来控制第二个柱子和第三个柱子的位置。另外,可以使用`legend`方法来添加图例,使用`xlabel`和`ylabel`方法来添加坐标轴标签,使用`title`方法来添加图表标题。最后,调用`show`方法来显示图形。