matplotlib绘制从上往下的条形图
时间: 2023-08-17 11:11:22 浏览: 91
matplotlib_vertical_bars_matplotlibPython_
使用matplotlib绘制从上往下的条形图可以通过以下步骤实现:
1. 导入matplotlib.pyplot模块
```python
import matplotlib.pyplot as plt
```
2. 准备数据,例如一个包含不同城市人口数量的字典
```python
population = {'Beijing': 2154, 'Shanghai': 2424, 'Guangzhou': 1500, 'Shenzhen': 1303}
```
3. 将字典转换成两个列表,一个是城市列表,一个是人口数量列表
```python
cities = list(population.keys())
population_num = list(population.values())
```
4. 创建画布和子图对象
```python
fig, ax = plt.subplots()
```
5. 使用barh方法绘制条形图,其中y轴必须反转,以使条形从上往下排列
```python
ax.barh(cities, population_num)
ax.invert_yaxis() # 反转y轴
```
6. 添加图表标题和轴标签
```python
ax.set_title('Population of Major Cities in China')
ax.set_xlabel('Population')
ax.set_ylabel('City')
```
7. 显示图表
```python
plt.show()
```
完整的代码如下:
```python
import matplotlib.pyplot as plt
population = {'Beijing': 2154, 'Shanghai': 2424, 'Guangzhou': 1500, 'Shenzhen': 1303}
cities = list(population.keys())
population_num = list(population.values())
fig, ax = plt.subplots()
ax.barh(cities, population_num)
ax.invert_yaxis()
ax.set_title('Population of Major Cities in China')
ax.set_xlabel('Population')
ax.set_ylabel('City')
plt.show()
```
阅读全文