Python画双正负柱状图
时间: 2023-11-05 07:53:18 浏览: 55
要画双正负柱状图,你可以使用 matplotlib 库。下面是一个简单示例代码:
```python
import matplotlib.pyplot as plt
# 数据
categories = ['A', 'B', 'C', 'D', 'E']
positive_values = [5, 8, 3, 7, 2]
negative_values = [-3, -5, -1, -4, -2]
# 创建画布
fig, ax = plt.subplots()
# 绘制正柱状图
ax.bar(categories, positive_values, color='green', label='Positive')
# 绘制负柱状图
ax.bar(categories, negative_values, color='red', label='Negative')
# 添加网格线
ax.grid(True)
# 添加标题和标签
plt.title('Double Bar Chart')
plt.xlabel('Categories')
plt.ylabel('Values')
# 添加图例
plt.legend()
# 显示图形
plt.show()
```
你可以根据自己的数据和需求修改这个示例代码以满足你的要求。
相关问题
python画双折线柱状图
您可以使用Python中的Matplotlib库来绘制双折线柱状图。以下是一个示例代码,用于绘制一个简单的双折线柱状图:
```python
import matplotlib.pyplot as plt
# 数据
categories = ['A', 'B', 'C', 'D', 'E']
values1 = [10, 15, 7, 12, 9]
values2 = [8, 11, 9, 6, 13]
# 创建图形
fig, ax1 = plt.subplots()
# 绘制柱状图
ax1.bar(categories, values1, label='Value 1')
ax1.set_ylabel('Value 1')
# 创建第二个y轴
ax2 = ax1.twinx()
# 绘制折线图
ax2.plot(categories, values2, color='red', marker='o', label='Value 2')
ax2.set_ylabel('Value 2')
# 添加图例
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
# 设置标题
plt.title('Dual Line Bar Chart')
# 展示图形
plt.show()
```
在这个示例中,我们使用了两个数据集`values1`和`values2`来绘制双折线柱状图。通过`bar`函数绘制柱状图,并使用`twinx`函数创建第二个y轴来绘制折线图。最后,通过`legend`函数添加图例,并使用`title`函数设置标题。您可以根据自己的需求修改数据和样式。
python怎么画双柱状图
你可以使用 Python 中的 Matplotlib 库来画双柱状图,首先导入该库并设定数据:
import matplotlib.pyplot as plt
labels = ['A', 'B', 'C', 'D']
values1 = [10, 20, 15, 25]
values2 = [20, 25, 10, 15]
然后使用下面的代码画双柱状图:
fig, ax = plt.subplots()
ax.bar(labels, values1, width=0.4, align='edge', label='First')
ax.bar(labels, values2, width=-0.4, align='edge', label='Second')
ax.legend()
plt.show()
这将会生成一个带有两个组的双柱状图,其中每个组中包含 A、B、C 和 D 四个类别。注意 width 的值是两个柱状图中间的距离,负号可以让第二个组的柱状图靠近第一个组。