python 画柱状图 以行名分组

以下是完全来自AI的脚本,给到的指令是:

python 脚本,柱状图,我有一个多年份的统计表,输入文件第一列为横坐标“药物”,输入文件第二列及之后的列为每一年的数据,每一行的数据为一种药物对应的多年份的耐药数据,每个单元格对应的是该药物的耐药个数,及占总数的比列,百分比列写在了中文的括号内。请画每年的每种药物的耐药个数及比例的柱状图,我的输入文件是“test.xlsx”

输入示例:

药物 2022 2023 2024
药物1 3 (25%) 4 (55%) 3 (25%)
药物2 3 (25%) 4 (35%) 2 (15%)

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.font_manager import FontProperties
# 设置字体为中文字体,如果需要修改宋体为其他字体,可将'SimSun'改为‘Microsoft YaHei’,'SimHei'
plt.rcParams['font.sans-serif'] = ['SimSun']

# 从Excel读取数据
df = pd.read_excel('test.xlsx')

# 提取需要的列数据
years = df.columns[1:]  # 年份
drugs = df.iloc[:, 0].tolist()  # 药物名称

# 提取耐药个数和占比
resistance_counts = df.iloc[:, 1:].applymap(lambda x: int(x.split('(')[0]))  # 耐药个数
percentages = df.iloc[:, 1:].applymap(lambda x: float(x.split('(')[1].replace(')', '')))  # 占比

# 设置中文字体,可去掉,和rcParams冲突;
font_prop = FontProperties(fname=r'C:\Windows\Fonts\SimSun.ttc', size=8)


# 绘制柱状图
fig, ax = plt.subplots(figsize=(12, 6))

total_bars = len(drugs)
bar_width = 0.8 / total_bars
opacity = 0.8
index = np.arange(len(years))

for i in range(total_bars):
    x = index + i * bar_width
    y = percentages.iloc[i].tolist()
    ax.bar(x, y, bar_width, alpha=opacity, label=drugs[i])

   # 标注百分比在柱子中间
    for j, v in enumerate(y):
       ax.text(x[j] + bar_width / 2, v + 0.5, f'{v:.2f}%', ha='center', va='bottom',rotation=60, fontproperties=font_prop)

ax.margins(y=0.2) 
# 设置图表标题和标签
ax.set_xlabel('年份', fontproperties=font_prop)
ax.set_ylabel('耐药比例 (%)', fontproperties=font_prop)
ax.set_title('每年每种药物的耐药个数及比例柱状图', fontproperties=font_prop)
ax.set_xticks(index + (total_bars - 1) * bar_width / 2)
ax.set_xticklabels(years, fontproperties=font_prop)

# 设置图例
ax.legend(loc='upper left', bbox_to_anchor=(1, 1))
# 调整图像布局,增加柱状图上方和图的上边框的边距
#plt.subplots_adjust(top=0.9, bottom=0.1)
# 调整图像布局
plt.tight_layout()

# 保存为PNG图片并设置足够宽的dpi
plt.savefig('result.png', dpi=300)  # 图片保存路径和文件名
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容