Python绘制四种柱状图(2) - 基于表格数据

1. Python基于表格数据绘制简单柱状图

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'x': ['A', 'B', 'C', 'D', 'E'],
                   'y': [50, 30, 70, 80, 60]})

plt.bar(df['x'], df['y'], align='center', width=0.5, color='b', label='data')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Bar chart')
plt.legend()
plt.show()

2. Python基于表格数据绘制堆积柱状图

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'x': ['A', 'B', 'C', 'D', 'E'],
                   'y1': [50, 30, 70, 80, 60],
                   'y2': [20, 40, 10, 50, 30]})

plt.bar(df['x'], df['y1'], align='center', width=0.5, color='b', label='Series 1')
plt.bar(df['x'], df['y2'], bottom=df['y1'], align='center', width=0.5, color='g', label='Series 2')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Stacked Bar Chart')
plt.legend()
plt.show()

3. Python基表格数据绘制分组柱状图

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 准备数据
df = pd.DataFrame({
    'group': ['G1', 'G2', 'G3', 'G4', 'G5'],
    'men_means': [20, 35, 30, 35, 27],
    'women_means': [25, 32, 34, 20, 25]
})
ind = np.arange(len(df))  # x 轴位置
width = 0.35  # 每个柱的宽度

# 绘制柱状图
fig, ax = plt.subplots()
rects1 = ax.bar(ind, df['men_means'], width, color='r')
rects2 = ax.bar(ind + width, df['women_means'], width, color='y')

# 添加标签、图例和轴标签
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(df['group'])
ax.legend((rects1[0], rects2[0]), ('Men', 'Women'))
ax.set_xlabel('Groups')
ax.set_ylabel('Scores')

# 显示图形
plt.show()

4. Python基于表格数据绘制百分比堆积柱状图

import matplotlib.pyplot as plt
import pandas as pd

# 准备数据
df = pd.DataFrame({
    'x': ['Group 1', 'Group 2', 'Group 3', 'Group 4', 'Group 5'],
    'y1': [10, 20, 30, 25, 30],
    'y2': [20, 25, 30, 15, 20],
    'y3': [30, 30, 25, 20, 10]
})

# 计算每个组的百分比
y_percent = df.iloc[:, 1:].div(df.iloc[:, 1:].sum(axis=1), axis=0) * 100

# 绘制堆积柱状图
fig, ax = plt.subplots()
ax.bar(df['x'], y_percent.iloc[:, 0], label='Series 1', color='r')
ax.bar(df['x'], y_percent.iloc[:, 1], bottom=y_percent.iloc[:, 0], label='Series 2', color='g')
ax.bar(df['x'], y_percent.iloc[:, 2], bottom=y_percent.iloc[:, :2].sum(axis=1), label='Series 3', color='b')


# 显示图形
plt.show()

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LucaTech

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值