用python绘制柱状图、条形图;多数据并列柱状图、多数据并列条形图;堆积柱状图、堆积条形图。
时间: 2024-06-12 22:09:05 浏览: 146
绘制柱状图和条形图可以使用Python的Matplotlib库。下面是示例代码分别绘制柱状图、条形图、多数据并列柱状图、多数据并列条形图、堆积柱状图和堆积条形图的方法:
1. 绘制柱状图:
```python
import matplotlib.pyplot as plt
x = ['A', 'B', 'C', 'D', 'E']
y = [5, 10, 8, 12, 6]
plt.bar(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Bar Chart')
plt.show()
```
2. 绘制条形图:
```python
import matplotlib.pyplot as plt
x = ['A', 'B', 'C', 'D', 'E']
y = [5, 10, 8, 12, 6]
plt.barh(x, y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Barh Chart')
plt.show()
```
3. 绘制多数据并列柱状图:
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(5)
width = 0.35
y1 = [5, 10, 8, 12, 6]
y2 = [3, 6, 9, 15, 12]
plt.bar(x - width/2, y1, width, label='Group 1')
plt.bar(x + width/2, y2, width, label='Group 2')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Grouped Bar Chart')
plt.xticks(x, ['A', 'B', 'C', 'D', 'E'])
plt.legend()
plt.show()
```
4. 绘制多数据并列条形图:
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(5)
width = 0.35
y1 = [5, 10, 8, 12, 6]
y2 = [3, 6, 9, 15, 12]
plt.barh(x - width/2, y1, width, label='Group 1')
plt.barh(x + width/2, y2, width, label='Group 2')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Grouped Barh Chart')
plt.yticks(x, ['A', 'B', 'C', 'D', 'E'])
plt.legend()
plt.show()
```
5. 绘制堆积柱状图:
```python
import numpy as np
import matplotlib.pyplot as plt
x = ['A', 'B', 'C', 'D', 'E']
y1 = [5, 10, 8, 12, 6]
y2 = [3, 6, 9, 15, 12]
plt.bar(x, y1, label='Group 1')
plt.bar(x, y2, bottom=y1, label='Group 2')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Stacked Bar Chart')
plt.legend()
plt.show()
```
6. 绘制堆积条形图:
```python
import numpy as np
import matplotlib.pyplot as plt
x = ['A', 'B', 'C', 'D', 'E']
y1 = [5, 10, 8, 12, 6]
y2 = [3, 6, 9, 15, 12]
plt.barh(x, y1, label='Group 1')
plt.barh(x, y2, left=y1, label='Group 2')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Stacked Barh Chart')
plt.legend()
plt.show()
```
阅读全文