matplotlib绘制 2021 年和 2020 年全国各地区 GDP 柱形图
时间: 2024-09-07 19:05:19 浏览: 110
要使用matplotlib绘制2021年和2020年全国各地区的GDP柱状图,你需要按照以下步骤操作:
首先,确保已经安装了`pandas`, `matplotlib`, 和 `numpy`库,如果没有,可以使用以下命令安装:
```bash
pip install pandas matplotlib numpy
```
然后,假设你有一个包含2020和2021年各地区GDP数据的数据框(df),其中有两个列分别为'地区名'和'GDP',分别表示地区和对应的GDP值。你可以这样做:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 假设数据存储在一个CSV文件中
data = pd.read_csv('gdp_data.csv') # 替换为实际文件路径
# 提取2020和2021年的数据
year_2020 = data[data['年份'] == '2020']
year_2021 = data[data['年份'] == '2021']
# 绘制柱状图
fig, ax = plt.subplots()
ax.barh(year_2020['地区名'], year_2020['GDP'], label='2020', color='blue')
ax.barh(year_2021['地区名'], year_2021['GDP'], left=year_2020['GDP'], label='2021', color='orange')
# 添加标题、轴标签和图例
plt.title('2020年与2021年全国各地区GDP对比')
ax.set_xlabel('GDP(亿元)')
ax.set_ylabel('地区')
ax.legend()
# 显示图表
plt.show()
```
阅读全文
相关推荐


















