# -*- coding: GBK -*- import pandas as pd import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties plt.rcParams['font.sans-serif'] = ['SimHei'] # 用黑体显示中文 plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 data = pd.read_csv('changsha天气.csv', encoding='GBK')['天气'].tolist() # 统计天气种类及次数 weather_counts = {} for weather in data: if weather in weather_counts: weather_counts[weather] += 1 else: weather_counts[weather] = 1 # 绘制饼图 plt.figure(figsize=(15,15 )) threshold = 0.05 # 设定显示阈值为5% def custom_autopct(pct): """ 自定义autopct逻辑,用于控制百分比标签的显示。 如果百分比小于阈值,则返回空字符串(即不显示标签)。 """ return ('%1.1f%%' % pct) if pct >= threshold else '' labels_to_show = [label for label, count in weather_counts.items() if count/sum(weather_counts.values()) >= threshold] values_to_show = [count for label, count in weather_counts.items() if label in labels_to_show] legend_labels = [label for label in weather_counts.keys() if label in labels_to_show] patches, texts, autotexts = plt.pie(weather_counts.values(), autopct=custom_autopct, startangle=140) plt.legend(patches,weather_counts.keys(), title="Weather Types", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1)) plt.title('Weather Distribution') plt.savefig('长沙2023年气温饼图.png') plt.show()