用matplotlib绘制热狗大胃王比赛水平交错柱状图,利用数据集导入
时间: 2023-11-04 17:02:53 浏览: 190
下面是使用matplotlib绘制热狗大胃王比赛水平交错柱状图的代码,数据集导入使用pandas库:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 读取数据集
df = pd.read_csv('hot_dog_winners.csv')
# 提取比赛年份和男子和女子比赛的热狗数
years = df['Year']
men_dogs = df['Men']
women_dogs = df['Women']
# 设置柱状图的宽度
bar_width = 0.4
# 设置男子比赛的柱状图
men_bar = plt.bar(years, men_dogs, width=bar_width, color='b', align='center')
# 设置女子比赛的柱状图
women_bar = plt.bar(years + bar_width, women_dogs, width=bar_width, color='r', align='center')
# 设置x轴和y轴标签
plt.xlabel('Year')
plt.ylabel('Hot Dogs Eaten')
# 设置图例
plt.legend((men_bar, women_bar), ('Men', 'Women'))
# 显示图形
plt.show()
```
这个代码将会绘制一个水平交错柱状图,其中蓝色柱子代表男子比赛的热狗数,红色柱子代表女子比赛的热狗数。每个柱子表示一个比赛年份。
相关问题
用matplotlib绘制热狗大胃王比赛水平交错柱状图,利用数据集hot-dog-contest-winner.csv导入
首先需要导入需要的库和数据集:
``` python
import pandas as pd
import matplotlib.pyplot as plt
# 导入数据集
data = pd.read_csv('hot-dog-contest-winners.csv')
```
接下来,我们需要对数据进行处理,将不同年份的冠军选手的数据分别提取出来,并计算出他们的比赛成绩:
``` python
# 获取不同年份的冠军选手数据
years = data['Year'].unique()
# 计算每个选手的比赛成绩
winners = []
for year in years:
temp_data = data[data['Year'] == year]
winner = temp_data.loc[temp_data['Dogs'] == temp_data['Dogs'].max()]
winners.append(winner)
# 将每个选手的比赛成绩存储在一个列表中
scores = []
for winner in winners:
score = winner['Dogs'].values[0]
scores.append(score)
# 将年份和比赛成绩存储在一个字典中
data_dict = {'Year': years, 'Score': scores}
df = pd.DataFrame(data_dict)
```
最后,我们可以利用matplotlib绘制交错柱状图:
``` python
# 绘制交错柱状图
fig, ax = plt.subplots(figsize=(12, 8))
ax.bar(df[df['Year'] % 2 == 0]['Year'], df[df['Year'] % 2 == 0]['Score'], color='red', label='Even Years')
ax.bar(df[df['Year'] % 2 != 0]['Year'], df[df['Year'] % 2 != 0]['Score'], color='blue', label='Odd Years')
ax.set_xlabel('Year')
ax.set_ylabel('Score')
ax.set_title('Hot Dog Eating Contest Winners')
ax.legend()
plt.show()
```
结果如下所示:
![热狗大胃王比赛水平交错柱状图](https://i.imgur.com/o8b0SHM.png)
用matplotlib.pyplot绘画水平交错柱状图,用导入的热狗大胃王数据
以下是使用热狗大胃王数据绘制水平交错柱状图的代码:
```python
import matplotlib.pyplot as plt
import pandas as pd
# 导入热狗大胃王数据
data = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Hot%20Dogs/hotdog-contest-winners.csv')
# 取出需要绘制的数据
names = data['Year'].tolist()
dogs = data['Dogs'].tolist()
buns = data['Buns'].tolist()
# 绘制水平交错柱状图
fig, ax = plt.subplots(figsize=(10, 6))
ax.barh(names, dogs, height=0.5, label='Hot Dogs')
ax.barh(names, buns, height=0.5, left=dogs, label='Buns')
ax.set_ylabel('Year')
ax.set_xlabel('Number of Hot Dogs/Buns Eaten')
ax.set_title('Hot Dog Eating Contest Winners')
ax.legend()
plt.show()
```
结果如下图所示:
![image](https://user-images.githubusercontent.com/26833433/136672274-2e8d0dff-b5b6-400e-9d1d-9441b0daa6f5.png)
阅读全文