# Group by 销售日期 and 分类名称 and sum the sales volumecategory_date_sales = merged_datagroupby销售日期 分类名称销量千克sumreset_index# Plottingpltfigurefigsize=16 8for category in category_date_sales分类名称unique subs
这个报错是由于当前字体库中缺少了字符"销"的字形导致的。可以尝试以下解决方法:
- 更换字体库:在代码的开头添加以下代码,将字体库更换为支持中文字符的字体,如SimHei、Microsoft YaHei等。
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 更换字体库为SimHei
- 使用Unicode编码:将"销售日期"和"分类名称"中的中文字符使用Unicode编码表示,例如"\u9500\u552e\u65e5\u671f"代替"销售日期","\u5206\u7c7b\u540d\u79f0"代替"分类名称"。
修改后的代码如下:
# Group by '\u9500\u552e\u65e5\u671f' and '\u5206\u7c7b\u540d\u79f0' and sum the sales volume
category_date_sales = merged_data.groupby(['\u9500\u552e\u65e5\u671f', '\u5206\u7c7b\u540d\u79f0'])['\u9500\u91cf(\u5343\u514b)'].sum().reset_index()
# Plotting
plt.figure(figsize=(16, 8))
for category in category_date_sales['\u5206\u7c7b\u540d\u79f0'].unique():
subset = category_date_sales[category_date_sales['\u5206\u7c7b\u540d\u79f0'] == category]
plt.plot(subset['\u9500\u552e\u65e5\u671f'], subset['\u9500\u91cf(\u5343\u514b)'], label=category)
plt.title('按时间分类的销售量趋势')
plt.xlabel('时间')
plt.ylabel('销量 (kg)')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
# Pivot table to get sales data in wide format for correlation analysis
correlation_data = category_date_sales.pivot(index='\u9500\u552e\u65e5\u671f', columns='\u5206\u7c7b\u540d\u79f0', values='\u9500\u91cf(\u5343\u514b)')
# Compute the correlation matrix
correlation_matrix = correlation_data.corr()
# Plot the heatmap for correlation matrix
plt.figure(figsize=(10, 6))
plt.title('Correlation Between Sales Volumes of Different Categories')
plt.xticks(rotation=45)
plt.yticks(rotation=45)
cax = plt.matshow(correlation_matrix, cmap='coolwarm', vmin=-1, vmax=1)
plt.colorbar(cax)
plt.xticks(range(len(correlation_matrix.columns)), correlation_matrix.columns)
plt.yticks(range(len(correlation_matrix.columns)), correlation_matrix.columns)
plt.show()
通过以上修改,代码中的中文字符将被替换为Unicode编码,可以避免报错。
原文地址: https://www.cveoy.top/t/topic/i2hC 著作权归作者所有。请勿转载和采集!