以下是完全來自AI的腳本,給到的指令是:
python 腳本,柱狀圖,我有一個(gè)多年份的統(tǒng)計(jì)表,輸入文件第一列為橫坐標(biāo)“藥物”,輸入文件第二列及之后的列為每一年的數(shù)據(jù),每一行的數(shù)據(jù)為一種藥物對應(yīng)的多年份的耐藥數(shù)據(jù),每個(gè)單元格對應(yīng)的是該藥物的耐藥個(gè)數(shù),及占總數(shù)的比列,百分比列寫在了中文的括號內(nèi)。請畫每年的每種藥物的耐藥個(gè)數(shù)及比例的柱狀圖,我的輸入文件是“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
# 設(shè)置字體為中文字體,如果需要修改宋體為其他字體,可將'SimSun'改為‘Microsoft YaHei’,'SimHei'
plt.rcParams['font.sans-serif'] = ['SimSun']
# 從Excel讀取數(shù)據(jù)
df = pd.read_excel('test.xlsx')
# 提取需要的列數(shù)據(jù)
years = df.columns[1:] # 年份
drugs = df.iloc[:, 0].tolist() # 藥物名稱
# 提取耐藥個(gè)數(shù)和占比
resistance_counts = df.iloc[:, 1:].applymap(lambda x: int(x.split('(')[0])) # 耐藥個(gè)數(shù)
percentages = df.iloc[:, 1:].applymap(lambda x: float(x.split('(')[1].replace(')', ''))) # 占比
# 設(shè)置中文字體,可去掉,和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])
# 標(biāo)注百分比在柱子中間
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)
# 設(shè)置圖表標(biāo)題和標(biāo)簽
ax.set_xlabel('年份', fontproperties=font_prop)
ax.set_ylabel('耐藥比例 (%)', fontproperties=font_prop)
ax.set_title('每年每種藥物的耐藥個(gè)數(shù)及比例柱狀圖', fontproperties=font_prop)
ax.set_xticks(index + (total_bars - 1) * bar_width / 2)
ax.set_xticklabels(years, fontproperties=font_prop)
# 設(shè)置圖例
ax.legend(loc='upper left', bbox_to_anchor=(1, 1))
# 調(diào)整圖像布局,增加柱狀圖上方和圖的上邊框的邊距
#plt.subplots_adjust(top=0.9, bottom=0.1)
# 調(diào)整圖像布局
plt.tight_layout()
# 保存為PNG圖片并設(shè)置足夠?qū)挼膁pi
plt.savefig('result.png', dpi=300) # 圖片保存路徑和文件名