# Python可视化 **Repository Path**: mengliyilei/python-visualization ## Basic Information - **Project Name**: Python可视化 - **Description**: 可视化项目 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-09-18 - **Last Updated**: 2024-12-30 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Python可视化 #### 介绍 Python实现基础的可视化项目 #### 安装教程 ##### 一、Python环境安装 1.下载环境 官网:https://www.python.org/ ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-09-28%20172442.png) 左侧为稳定版本,选择自己需要的版本下载即可。 ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-09-28%20172651.png) 2.环境变量配置 在电脑设置中搜索“环境变量” ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-09-28%20172936.png) 点击环境变量 ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-09-28%20172951.png) 选中 Path 进行编辑 ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-09-28%20173010.png) 选择新建,将之前下载的 Python 的文件路径添加进去,再将 Python 文件中 Bin 的文件路径添加进去,最后一路“确定”保存设置。 ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-09-28%20173105.png) ##### 二、安装 PyCharm 官网:https://www.jetbrains.com/pycharm/download/?section=windows 选择“社区版”安装(社区版免费)。 ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-09-28%20192713.png) 安装后,点击左下角设置。 ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-09-28%20192815.png) 在设置中找到“Python解释器” ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-09-28%20192859.png) 将下载的 Python 的文件路径添加进去,点击应用 ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-09-28%20192917.png) ##### 三、安装必要的库 ###### 1.安装基础画图库 matplotlib ``` pip install matplotlib ``` 查询版本号,是否安装成功 ``` import matplotlib print(matplotlib.__version__) ``` ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-10-06%20193229.png) ###### 2.安装有交互功能的图库 pyecharts ``` pip install pyecharts ``` 查询版本号,是否安装成功 ``` import pyecharts print(pyecharts.__version__) ``` ![输入图片说明](%E5%9B%BE%E7%89%87/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-10-06%20193513.png) #### 可视化项目 ##### 一、柱形图 ###### 1.渐变柱形图 ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据 data = pd.read_excel('第二章 图表(前15).xlsx',sheet_name='1 渐变柱形图',usecols='B:C',skiprows=1) # 设置渐变函数 def gradient_bar(x, y, ax, colormap='Blues'): # 选用蓝色色卡 n_bars = len(x) bar_colors = plt.get_cmap(colormap)(np.linspace(0.5, 0.9, 100)) # 设置渐变起始点与终止点 # 创建柱子 for i in range(n_bars): left = i bottom = 0 width = 0.6 height = y[i] # 创建渐变效果 polys = [] for j in range(100): h = height * (j / 100) verts_j = [ (left, bottom + h), (left, bottom + height), (left + width, bottom + height), (left + width, bottom + h), (left, bottom + h) ] polys.append(verts_j) poly = PolyCollection(polys, facecolors=bar_colors) ax.add_collection(poly) ax.autoscale_view() # 创建图形和坐标轴 fig, ax = plt.subplots(figsize=(8, 6)) # 设置背景颜色 fig.patch.set_facecolor('#00002d') ax.set_facecolor('#00002d') # 设置X轴和Y轴数据 x = np.arange(len(data['区域'])) # X轴位置 y = data['销售量'] # Y轴高度 # 绘制渐变柱形图 gradient_bar(x, y, ax) # 设置X轴标签 ax.set_xticks(x+0.3) ax.set_xticklabels(data['区域'], color='w') # 设置Y轴标签颜色为白色 ax.set_yticklabels(ax.get_yticks(), color='w') # 添加网格线 ax.grid(True, axis='y' ,linestyle='--', linewidth=0.5, color='w') # 隐藏边框 for spine in ax.spines.values(): spine.set_visible(False) # 输出每个柱子的值 for i in range(len(x)): ax.text(x[i] + 0.3, y[i] + 0.1, f'{int(y[i])}', ha='center', va='bottom', color='w', fontsize=10) # 调整图形位置 plt.subplots_adjust(top=0.8) # 留出空间给标题 # 添加标题 plt.text(0, 1.15, '3月各区域销量分布', color='w', fontsize=24, transform=ax.transAxes) plt.text(0, 1.05, '东北销量最多占比总销量的22%,华南销量最低', color='w', fontsize=16, transform=ax.transAxes) # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章前15/图片/渐变柱形图.png', dpi=300, bbox_inches='tight', facecolor='#00002d') # 显示图形 plt.show() ``` ![输入图片说明](实验二/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E6%B8%90%E5%8F%98%E6%9F%B1%E5%BD%A2%E5%9B%BE.png) ###### 2.带均值柱形图 ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据 data = pd.read_excel('第二章 图表(前15).xlsx',sheet_name='1 渐变柱形图',usecols='B:C',skiprows=1) # 设置渐变函数 def gradient_bar(x, y, ax, colormap='Blues'): # 选用蓝色色卡 n_bars = len(x) bar_colors = plt.get_cmap(colormap)(np.linspace(0.5, 0.9, 100)) # 设置渐变起始点与终止点 # 创建柱子 for i in range(n_bars): left = i bottom = 0 width = 0.6 height = y[i] # 创建渐变效果 polys = [] for j in range(100): h = height * (j / 100) verts_j = [ (left, bottom + h), (left, bottom + height), (left + width, bottom + height), (left + width, bottom + h), (left, bottom + h) ] polys.append(verts_j) poly = PolyCollection(polys, facecolors=bar_colors) ax.add_collection(poly) ax.autoscale_view() # 创建图形和坐标轴 fig, ax = plt.subplots(figsize=(8, 6)) # 设置背景颜色 fig.patch.set_facecolor('#00002d') ax.set_facecolor('#00002d') # 设置X轴和Y轴数据 x = np.arange(len(data['区域'])) # X轴位置 y = data['销售量'] # Y轴高度 # 计算y的均值 y_mean = y.mean() # 绘制渐变柱形图 gradient_bar(x, y, ax) # 设置X轴标签 ax.set_xticks(x+0.3) ax.set_xticklabels(data['区域'], color='w') # 设置Y轴标签颜色为白色 ax.set_yticklabels(ax.get_yticks(), color='w') # 保留底部边框,隐藏其他边框 for spine in ax.spines.values(): if spine.spine_type == 'bottom': spine.set_color('white') # 设置底部边框颜色为白色 else: spine.set_visible(False) # 输出每个柱子的值 for i in range(len(x)): ax.text(x[i] + 0.3, y[i] + 0.1, f'{int(y[i])}', ha='center', va='bottom', color='w', fontsize=10) # 绘制y的均值水平线 ax.axhline(y=y_mean, color='red', linestyle='--', linewidth=2, label='平均值') # 添加均值的文本标注 ax.text(0.9, 0.75, f'平均值: {y_mean:.2f}', color='red', fontsize=12, transform=ax.transAxes) # 调整图形位置 plt.subplots_adjust(top=0.8) # 留出空间给标题 # 添加标题 plt.text(0, 1.15, '3月各区域销量分布', color='w', fontsize=24, transform=ax.transAxes) plt.text(0, 1.05, '东北销量最多占比总销量的22%,华南销量最低', color='w', fontsize=16, transform=ax.transAxes) # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章前15/图片/带均值柱形图.png', dpi=300, bbox_inches='tight', facecolor='#00002d') # 显示图形 plt.show() ``` ![输入图片说明](实验二/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%B8%A6%E5%9D%87%E5%80%BC%E6%9F%B1%E5%BD%A2%E5%9B%BE.png) ###### 3.渐变圆角柱形图 ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据 data = pd.read_excel('第二章 图表(前15).xlsx',sheet_name='3 渐变圆角柱形图',usecols='B:C',skiprows=1) # 设置渐变函数 def gradient_bar(x, y, ax, colormap='Blues'): # 选用蓝色色卡 n_bars = len(x) bar_colors = plt.get_cmap(colormap)(np.linspace(0.5, 0.9, 100)) # 设置渐变起始点与终止点 # 创建柱子 for i in range(n_bars): left = i bottom = 0 width = 0.6 height = y[i] # 创建渐变效果 polys = [] for j in range(100): h = height * (j / 100) verts_j = [ (left, bottom + h), (left, bottom + height), (left + width, bottom + height), (left + width, bottom + h), (left, bottom + h) ] polys.append(verts_j) poly = PolyCollection(polys, facecolors=bar_colors) ax.add_collection(poly) ax.autoscale_view() # 创建图形和坐标轴 fig, ax = plt.subplots(figsize=(8, 6)) # 设置背景颜色 fig.patch.set_facecolor('#00002d') ax.set_facecolor('#00002d') # 设置X轴和Y轴数据 x = np.arange(len(data['商品'])) # X轴位置 y = data['销量'] # Y轴高度 # 绘制渐变柱形图 gradient_bar(x, y, ax) # 设置X轴标签 ax.set_xticks(x+0.3) ax.set_xticklabels(data['商品'], color='w') # 设置Y轴标签颜色为白色 ax.set_yticklabels(ax.get_yticks(), color='w') # 添加网格线 ax.grid(True, axis='y' ,linestyle='--', linewidth=0.5, color='w') # 隐藏边框 for spine in ax.spines.values(): spine.set_visible(False) # 输出每个柱子的值 for i in range(len(x)): ax.text(x[i] + 0.3, y[i] + 0.1, f'{int(y[i])}', ha='center', va='bottom', color='w', fontsize=10) # 调整图形位置 plt.subplots_adjust(top=0.8) # 留出空间给标题 # 添加标题 plt.text(0, 1.15, '3月商品销量对比', color='w', fontsize=24, transform=ax.transAxes) plt.text(0, 1.05, '防晒销量最多,3月销量856;面膜最少,3月销量523', color='w', fontsize=16, transform=ax.transAxes) # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章前15/图片/渐变圆角柱形图.png', dpi=300, bbox_inches='tight', facecolor='#00002d') # 显示图形 plt.show() ``` ###### 4.标注柱形图 ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据 data = pd.read_excel('第二章 图表(前15).xlsx',sheet_name='4 标注柱形图',usecols='B:C',skiprows=1) # 创建图形和坐标轴 fig, ax = plt.subplots(figsize=(8, 6)) # 设置背景颜色 fig.patch.set_facecolor('#00002d') ax.set_facecolor('#00002d') # 设置X轴和Y轴数据 x = np.arange(len(data['月份'])) # X轴位置 y = data['销量'] # Y轴高度 # 绘制不同颜色的柱形图 bars = ax.bar(x, y, color=['red','navy','royalblue','green','teal','blue','purple','slateblue']) # 设置X轴标签 ax.set_xticks(x) ax.set_xticklabels(data['月份'], color='w') # 设置Y轴标签颜色为白色 ax.set_yticks(ax.get_yticks()) ax.set_yticklabels(ax.get_yticks(), color='w') # 添加网格线 ax.grid(True, axis='y' ,linestyle='--', linewidth=0.5, color='w') # 隐藏边框 for spine in ax.spines.values(): spine.set_visible(False) # 输出每个柱子的值 colors=['red','navy','royalblue','green','teal','blue','purple','slateblue'] for i in range(len(x)): facecolor = colors[i] ax.text(x[i], y[i]+300, f'{int(y[i])}', ha='center', color='w', fontsize=10, bbox=dict(facecolor=facecolor, boxstyle='round')) # 调整图形位置 plt.subplots_adjust(top=0.8) # 留出空间给标题 # 添加标题 plt.text(0, 1.15, '2021年商品销量情况', color='w', fontsize=24, transform=ax.transAxes) plt.text(0, 1.05, '口红销量最好达9221,是眼影最低值2645近3.5倍', color='w', fontsize=16, transform=ax.transAxes) # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章前15/图片/标注柱形图.png', dpi=300, bbox_inches='tight', facecolor='#00002d') # 显示图形 plt.show() ``` ![输入图片说明](实验二/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E6%A0%87%E6%B3%A8%E6%9F%B1%E5%BD%A2%E5%9B%BE.png) ###### 5.层叠柱形图 ``` import pandas as pd from pyecharts.charts import Bar from pyecharts import options as opts # 导入数据 data = pd.read_excel('第二章 图表(前15).xlsx',sheet_name='5 层叠柱形图',usecols='B:D',skiprows=1) # 数据准备 categories = data['季度'].tolist() values1 = data['销售额'].tolist() values2 = data['利润额'].tolist() # 创建柱状图 bar = ( Bar(init_opts=opts.InitOpts(bg_color='#00002d')) .add_xaxis(categories) # 设置 x 轴数据 .add_yaxis("销售额", values1, gap='-30%', color='blue') .add_yaxis("利润额", values2, gap='-30%', color='red') .set_global_opts( # 设置标题 title_opts=opts.TitleOpts( title="2021年至今季度销售额(万)和利润额(万)", title_textstyle_opts=opts.TextStyleOpts(color="white", font_size=24), subtitle="2022年第二季度销售额首次出现下降,降幅达到15%", subtitle_textstyle_opts=opts.TextStyleOpts(color="white", font_size=16) ), # 设置交互按钮 legend_opts=opts.LegendOpts( is_show=True, textstyle_opts=opts.TextStyleOpts(color="white"), pos_right="0%", pos_top="5%" ), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"), xaxis_opts=opts.AxisOpts( axisline_opts=opts.AxisLineOpts(is_show=True), # X 轴线 axislabel_opts=opts.LabelOpts(is_show=True, color='white'), # X 轴标签 splitline_opts=opts.SplitLineOpts(is_show=False) # X 轴网格线 ), yaxis_opts=opts.AxisOpts( axisline_opts=opts.AxisLineOpts(is_show=False), # Y 轴线 axislabel_opts=opts.LabelOpts(is_show=False), # Y 轴标签 splitline_opts=opts.SplitLineOpts(is_show=False) # Y 轴网格线 ) ) .set_series_opts( label_opts=opts.LabelOpts( is_show=True, position='top', color='white') # 显示数据 ) ) # 导出交互的 HTML 文件 bar.render("D:/python charm/01/可视化/第二章前15/图片/层叠柱形图.html") ``` 运行结果在“实验二”文件夹的“运行结果”文件夹中。 ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%BA%8C/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-10-06%20195916.png) ##### 二、折线图 ###### 1.平滑折线图 ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import make_interp_spline plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据与数据处理 data = pd.read_excel('第二章 图表(前15).xlsx',sheet_name='11 平滑折线图',usecols='B:D',skiprows=1) data['月份'] = data['月份'].str.extract(r'^(.*)月').astype(int) x1 = data['月份'].values[0:8] x2 = data['月份'].values[8:] +12 x = [*x1, *x2] y = data['销量'].values.tolist() # 插值使得折线平滑 spl = make_interp_spline(x, y, k=3) x_smooth = np.linspace(np.min(x), np.max(x), 500) y_smooth = spl(x_smooth) # 创建图形和坐标轴 fig, ax = plt.subplots(figsize=(10, 6)) # 设置背景颜色 fig.patch.set_facecolor('#00002d') ax.set_facecolor('#00002d') # 设置X轴标签 ax.set_xticks(x) ax.set_xticklabels(data['月份'], color='w') # 设置Y轴标签颜色为白色 ax.set_ylim(0, 4000) ax.set_yticks(ax.get_yticks()) ax.set_yticklabels(ax.get_yticks(), color='w') # 保留底部边框,隐藏其他边框 for spine in ax.spines.values(): if spine.spine_type == 'bottom': spine.set_color('white') # 设置底部边框颜色为白色 else: spine.set_visible(False) # 调整图形位置 plt.subplots_adjust(top=0.8) # 留出空间给标题 # 添加标题 plt.text(0, 1.15, '化妆品品类月度销量走势', color='w', fontsize=24, transform=ax.transAxes) plt.text(0, 1.05, '2022年销量迅速增加,1月最高,销量达到3782', color='w', fontsize=16, transform=ax.transAxes) # 绘制从最大y值到x轴的垂线 ax.axvline(x[y.index(np.max(y))], ymin=0, ymax=np.max(y) / 4000, color='white', linestyle='--') ax.annotate(f'{np.max(y)}', xy=(x[y.index(np.max(y))], np.max(y)), xytext=(x[y.index(np.max(y))], np.max(y) + 300), color='white', fontsize=12) # 绘制图 plt.plot(x_smooth, y_smooth, color='red', linewidth=2) # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章/图片/平滑折线图.png', dpi=300, bbox_inches='tight', facecolor='#00002d') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%B8%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%B9%B3%E6%BB%91%E6%8A%98%E7%BA%BF%E5%9B%BE.png) ###### 2.对比折线图 ``` import pandas as pd import matplotlib.pyplot as plt from qtawesome.iconic_font import text_color plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据与数据处理 data = pd.read_excel('第二章 图表(前15).xlsx',sheet_name='13 对比折线图',usecols='B:D',skiprows=1) x = data['月份'] y = data['2021年'] z = data['2022年'] # 创建图形和坐标轴 fig, ax = plt.subplots(figsize=(10, 6)) # 设置背景颜色 fig.patch.set_facecolor('#00002d') ax.set_facecolor('#00002d') # 设置X轴标签 ax.set_xticklabels(data['月份'], color='w') # 设置Y轴标签颜色为白色 ax.set_ylim(0, 3000) ax.set_yticklabels(ax.get_yticks(), color='w') # 添加网格线 ax.grid(True, axis='y' ,linestyle='--', linewidth=0.5, color='w') # 隐藏边框 for spine in ax.spines.values(): spine.set_visible(False) # 调整图形位置 plt.subplots_adjust(top=0.8) # 留出空间给标题 # 添加标题 plt.text(0, 1.15, '2022年上半年各月同比去年销量', color='w', fontsize=24, transform=ax.transAxes) plt.text(0, 1.05, '上半年同比去年增长明显,5月份同比增长最多,增长近40%', color='w', fontsize=16, transform=ax.transAxes) # 绘制图 plt.plot(x, y,'o-', color='tomato', linewidth=2, markeredgecolor='#00002d', label='2021年') plt.plot(x, z,'o-', color='dodgerblue', linewidth=2, markeredgecolor='#00002d', label='2022年') ax.legend(facecolor='#00002d', labelcolor='w') # 添加每个点的数值 for i in range(len(x)): plt.text(x[i], y[i] + 30, f'{int(y[i])}', color='w', fontsize=12, ha='center') plt.text(x[i], z[i] + 30, f'{int(z[i])}', color='w', fontsize=12, ha='center') # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章/图片/对比折线图.png', dpi=300, bbox_inches='tight', facecolor='#00002d') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%B8%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%AF%B9%E6%AF%94%E6%8A%98%E7%BA%BF%E5%9B%BE.png) ###### 3.折线柱形图 ``` import pandas as pd import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据 data = pd.read_excel('第二章 图表(后15).xlsx',sheet_name='23 柱形折线图',usecols='B:D',skiprows=1) print(data) # 数据准备 x = data['年份'].tolist() y = data['销售量'].tolist() z = (data['同比']).tolist() # 创建图形和坐标轴 fig, ax = plt.subplots(figsize=(8, 6)) # 设置背景颜色 fig.patch.set_facecolor('#00002d') ax.set_facecolor('#00002d') # 隐藏边框 for spine in ax.spines.values(): spine.set_visible(False) # 设置X轴标签 ax.set_xticks(x) ax.set_xticklabels(data['年份'], color='w') # 设置Y轴标签颜色为白色 ax.set_yticks([]) ax.set_ylim(0, 7000) ax.set_yticklabels(ax.get_yticks(), color='w') # 绘制柱形图 bars = ax.bar(x,y, color='dodgerblue', width=0.3, label='销售量') # 输出每个柱子的值 for i in range(len(x)): ax.text(x[i], y[i], f'{int(y[i])}', ha='center', va='bottom', color='w', fontsize=10) # 创建第二个坐标轴 ax2 = ax.twinx() # 设置范围 ax2.set_ylim(min(z) * (-10), max(z) * 1.2) # 绘制折线图 ax2.plot(x, z,'o-', color='tomato', linewidth=2, markeredgecolor='#00002d', label='同比') # 输出每个点的值 for i in range(len(x)): ax2.text(x[i], z[i] + 0.02, f'{int(z[i] * 100)}%', ha='center', color='w', fontsize=10) # 调整图形位置 plt.subplots_adjust(top=0.8) # 留出空间给标题 # 添加标题 plt.text(0, 1.15, '近六年销售量及增长率', color='w', fontsize=24, transform=ax.transAxes) plt.text(0, 1.05, '平台销量近6年持续增长,但近两年增长率有所放缓', color='w', fontsize=16, transform=ax.transAxes) # 添加图例 lines, labels = ax.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax2.legend(lines + lines2, labels + labels2, loc='best', facecolor='#00002d', labelcolor='w') # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章/图片/柱形折线图.png', dpi=300, bbox_inches='tight', facecolor='#00002d') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%B8%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E6%9F%B1%E5%BD%A2%E6%8A%98%E7%BA%BF%E5%9B%BE.png) ##### 三、饼图 ###### 1.南丁格尔圆饼图 ``` import pandas as pd from pyecharts.charts import Pie from pyecharts import options as opts # 导入数据 data = pd.read_excel('第二章 图表(后15).xlsx',sheet_name='19 南丁格尔圆饼图',usecols='B:C',skiprows=1) # 准备数据 x = data['部门'].tolist() y = data['人数占比'].tolist() # 创建南丁格尔圆饼图 pie = ( Pie(init_opts=opts.InitOpts(bg_color='#00002d')) .add("", [list(z) for z in zip(x, y)]) .set_global_opts( title_opts=opts.TitleOpts( title="2021年各部门人数分布", title_textstyle_opts=opts.TextStyleOpts(color="white", font_size=24), ), legend_opts=opts.LegendOpts( pos_top="5%", pos_right="5%", textstyle_opts=opts.TextStyleOpts(color="white") ) ) .set_series_opts( label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"), radius=["0%", "75%"], rosetype="radius" ) ) # 渲染图表 pie.render("D:/python charm/01/可视化/第二章/图片/南丁格尔圆饼图.html") ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%B8%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-10-10%20162659.png) ###### 2.南丁格尔玫瑰图 ``` import pandas as pd from pyecharts.charts import Pie from pyecharts import options as opts # 导入数据 data = pd.read_excel('第二章 图表(后15).xlsx',sheet_name='20 南丁格尔(PPT)',usecols='B:C',skiprows=1) # 准备数据 x = data['部门'].tolist() y = data['人数占比'].tolist() # 创建南丁格尔玫瑰图 rose_chart = ( Pie(init_opts=opts.InitOpts(bg_color='#00002d')) .add("", [list(z) for z in zip(x, y)], rosetype="area", ) .set_global_opts( title_opts=opts.TitleOpts( title="2021年各部门人数分布", title_textstyle_opts=opts.TextStyleOpts(color="white", font_size=24), ), legend_opts=opts.LegendOpts( pos_top="5%", pos_right="5%", textstyle_opts=opts.TextStyleOpts(color="white") ) ) .set_series_opts( label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"), ) .set_colors( ['rgb({r},0,{b})'.format(r=255-20*(len(y)-x+1), b=255-15*x) for x in range(len(y))] ) ) # 渲染图表 rose_chart.render("D:/python charm/01/可视化/第二章/图片/南丁格尔不等半径圆饼图.html") ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%B8%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-10-10%20162718.png) ##### 四、蝴蝶图、数值百分比、对比柱形图、甘特图 ###### 1.蝴蝶图 ``` import pandas as pd import matplotlib.pyplot as plt # 设置中文字体 plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据 data = pd.read_excel('第二章 图表(前15).xlsx', sheet_name='6 蝴蝶图', usecols='B:F', skiprows=1) # 创建图形和轴 fig, ax = plt.subplots(figsize=(10, 6)) # 设置条形图的宽度 bar_width = 0.4 index = range(len(data)) # 计算条形图的偏移量 offset = bar_width * 500 # 增加偏移量,使条形图之间有更大的间隔 # 绘制2022年的条形图 bars1 = ax.barh(index, data['2022年销量']+offset, bar_width, color='skyblue', label='2022', left=offset) # 绘制2021年的条形图 bars2 = ax.barh(index, -(data['2021年销量']+offset), bar_width, color='lightgreen', label='2021', left=-offset) # 添加标题和标签 ax.set_title('2022年与2021年数据对比') # 设置Y轴标签 ax.set_yticks(index) ax.set_yticklabels([]) # 清空Y轴标签 # 在条形图中间添加Y轴标签 for i, region in enumerate(data['区域']): ax.text(0, i, region, ha='center', va='center', color='black') # 在条形图中输出2021年和2022年的销量值 for i, (value2021, value2022) in enumerate(zip(data['2021年销量'], data['2022年销量'])): # 2021年销量值 ax.text(-value2021 - offset - 0.1, i, f'{value2021}', ha='right', va='center', color='black') # 2022年销量值 ax.text(value2022 + offset + 0.1, i, f'{value2022}', ha='left', va='center', color='black') # 隐藏边框 for spine in ax.spines.values(): spine.set_visible(False) # 隐藏X轴和Y轴 ax.axis('off') # 反转X轴,使2021年的条形图向左显示 ax.invert_xaxis() # 将图例输出在条形图的上方 ax.legend(loc='upper center', bbox_to_anchor=(1, 1.1), ncol=2) # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章/图片/对称条形图.png', dpi=300, bbox_inches='tight') # 显示图形 plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%9B%9B/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%AF%B9%E7%A7%B0%E6%9D%A1%E5%BD%A2%E5%9B%BE.png) ###### 2.数值百分比 ``` import pandas as pd import matplotlib.pyplot as plt # 设置中文字体 plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据 data = pd.read_excel('第二章 图表(前15).xlsx', sheet_name='8 数值百分比', usecols='B:F', skiprows=1) # 创建图形和轴 fig, ax = plt.subplots(figsize=(10, 6)) # 设置条形图的宽度 bar_width = 0.4 index = range(len(data)) bars1 = ax.barh(index, data['销量'], bar_width, color='skyblue', label='销量') bars2 = ax.barh(index, 500, bar_width, color='lightgreen', label='同比去年', left=max(data['销量'])) # 添加标题和标签 ax.set_title('2021年各区域销量及同比情况') # 设置Y轴标签 ax.set_yticks(index) ax.set_yticklabels(data['区域']) # 隐藏边框 for spine in ax.spines.values(): spine.set_visible(False) # 隐藏X轴 ax.xaxis.set_visible(False) for i, bar in enumerate(bars1): ax.text(bar.get_width(), bar.get_y() + bar.get_height() / 2, f"{data['销量'][i]}", va='center', ha='right', color='black') for i, bar in enumerate(bars2): ax.text(max(data['销量']) + bar.get_width(), bar.get_y() + bar.get_height() / 2, f"{data['同比去年'][i] * 100:.1f}%", va='center', ha='right', color='black') # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章/图片/数值百分比图.png', dpi=300, bbox_inches='tight') # 显示图形 plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%9B%9B/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E6%95%B0%E5%80%BC%E7%99%BE%E5%88%86%E6%AF%94%E5%9B%BE.png) ###### 3.对比柱形图 ``` import pandas as pd import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据 data = pd.read_excel('第二章 图表(前15).xlsx', sheet_name='9 对比柱形图', usecols='B:E', skiprows=1) # 设置图形大小 plt.figure(figsize=(10, 6)) # 定义柱状图的宽度 bar_width = 0.35 # 计算每个商品的索引位置 index = range(len(data['商品'])) # 绘制2021年销量柱状图 plt.bar(index, data['2021销量'], bar_width, label='2021年销量', alpha=0.7) # 绘制2022年销量柱状图 plt.bar([i + bar_width for i in index], data['2022销量'], bar_width, label='2022年销量', alpha=0.7) # 添加数值标签 for i, v in enumerate(data['2021销量']): plt.text(i, v + 10, str(v), ha='center', va='bottom', fontsize=10) for i, v in enumerate(data['2022销量']): plt.text(i + bar_width, v + 10, str(v), ha='center', va='top', fontsize=10) # 计算2022年销量与2021年销量的差值 differences = data['2021销量'] - data['2022销量'] # 在2022年销量柱子上绘制向上的箭头,并输出差值 for i, diff in enumerate(differences): if diff > 0: plt.annotate(f'{diff}', xy=(i + bar_width, data['2021销量'][i]), # 箭头的终点位置 xytext=(i + bar_width, data['2022销量'][i] + 100), # 注释文本的位置 textcoords='data', arrowprops=dict(arrowstyle="<-", color='red'), ha='center', va='bottom', fontsize=10) # 添加标题和标签 plt.title('2021年与2022年销量对比') plt.xlabel('商品') plt.ylabel('销量') # 设置x轴刻度和标签 plt.xticks([i + bar_width / 2 for i in index], data['商品']) # 显示图例 plt.legend() # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章/图片/对比柱形图.png', dpi=300, bbox_inches='tight') # 显示图形 plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%9B%9B/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%AF%B9%E6%AF%94%E6%9F%B1%E5%BD%A2%E5%9B%BE.png) ###### 4.甘特图 ``` import pandas as pd import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据 data = pd.read_excel('第二章 图表(前15).xlsx', sheet_name='10 甘特图', usecols='B:G', skiprows=2) # 绘制甘特图 fig, ax = plt.subplots(figsize=(10, 6)) # 将日期字符串转换为日期对象 data['开始日期'] = pd.to_datetime(data['开始日期']) data['结束日期'] = pd.to_datetime(data['结束日期']) data['项目天数'] = data['项目天数'] # 绘制甘特图 ax.barh(data['项目名称'], data['项目天数'], left=data['开始日期']) ax.barh(data['项目名称'], data['进行天数'], left=data['开始日期'], color='skyblue') # 在柱子中输出完成度的值 for index, row in data.iterrows(): x = row['开始日期'] + pd.Timedelta(days=row['进行天数']) y = index ax.text(x, y, f"{row['完成度'] * 100:.0f}%", ha='center', va='center', color='white') # 设置图表标题和标签 ax.set_title('项目甘特图') ax.set_xlabel('日期') ax.set_ylabel('项目名称') # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章/图片/甘特图.png', dpi=300, bbox_inches='tight') # 显示图表 plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%9B%9B/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E7%94%98%E7%89%B9%E5%9B%BE.png) ##### 五、菱形走势图、单值圆环图、水球图 ###### 1.菱形走势图 ``` import pandas as pd import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 导入数据 data = pd.read_excel('第二章 图表(前15).xlsx', sheet_name='12 菱形走势图', usecols='B:C', skiprows=1) # 设置图形大小 plt.figure(figsize=(10, 6)) # 设置Y轴范围 plt.ylim(0, 1) # 绘制菱形走势图 plt.scatter(data.iloc[:, 0], data.iloc[:, 1], marker='d', s=100, facecolors='none', edgecolors='red') # 绘制从菱形到X轴的连线 for x, y in zip(data.iloc[:, 0], data.iloc[:, 1]): plt.plot([x, x], [0, y - 0.02], color='red', linestyle='-') plt.text(x, y + 0.02, f'{y * 100:.2f}%', ha='center', va='bottom', fontsize=10, color='green') # 隐藏除X轴以外的边框 ax = plt.gca() # 获取当前的坐标轴 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) # 隐藏Y轴标签 plt.yticks([]) # 导出图片 #plt.savefig('D:/python charm/01/可视化/第二章/图片/菱形走势图.png', dpi=300, bbox_inches='tight') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%BA%94/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E8%8F%B1%E5%BD%A2%E8%B5%B0%E5%8A%BF%E5%9B%BE.png) ###### 2.单值圆环图 ``` import pandas as pd import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False data = { '类别': ['完成率', '占位'], '数值': [85, 15] } df = pd.DataFrame(data) plt.figure(figsize=(6, 6)) colors = ['lightgreen', 'red'] #绘制饼图 plt.pie(df['数值'], autopct=None, startangle=-160, colors=colors) #绘制中心圆覆盖饼图中心 centre_circle = plt.Circle((0, 0), 0.8, fc='white') fig = plt.gcf() fig.gca().add_artist(centre_circle) total = np.sum(df['数值']) completed_percentage = df['数值'][0] / total * 100 #添加文字 plt.text(0, 0, f'{completed_percentage:.0f}%\n目标完成率', ha='center', va='center', fontsize=30, weight='bold') plt.axis('equal') plt.tight_layout() #plt.savefig('D:/python charm/01/可视化/第二章/图片/单值圆环图.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%BA%94/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%8D%95%E5%80%BC%E5%9C%86%E7%8E%AF%E5%9B%BE.png) ###### 3.水球图 ``` from pyecharts import options as opts from pyecharts.charts import Liquid #数据准备 completed_percentage = 65 auxiliary_percentage = 100 #绘制水球图 liquid = ( Liquid() .add("完成率", [completed_percentage / 100]) .set_global_opts(title_opts=opts.TitleOpts(title="完成率水球图")) ) #输出图表 #iquid.render("D:/python charm/01/可视化/第二章/图片/水球图.html") ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%BA%94/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-11-21%20205423.png) ##### 六、波浪水球图、玉玦图、跑道图 ###### 1.波浪水球图 ``` from pyecharts import options as opts from pyecharts.charts import Liquid completed_percentage = 65 colors = ["#599CB4"] liquid = ( Liquid() .add("完成率", [completed_percentage / 100], color=colors) # 设置颜色 .set_global_opts(title_opts=opts.TitleOpts(title="波浪水球图")) ) #显示图表 #liquid.render("D:/python charm/01/可视化/第二章/图片/波浪水球图.html") ``` ###### 2.玉玦图 ``` import matplotlib.pyplot as plt import numpy as np import matplotlib.patches as mpatches ages = ['>=50', '[40,50)', '[30,40)', '[20,30)'] percentages = [12.5, 20.8, 29.2, 37.5] colors = ['#F7C1CF', '#FFD47F', '#7B92C7', '#ADD9EE'] fig, ax = plt.subplots(figsize=(8, 8)) ring_width = 0.3 directions = [(-70, 90), (-110, 90), (-140, 90), (-180, 90)] for i, (age, percent, direction, color) in enumerate(zip(ages[::-1], percentages[::-1], directions[::-1], colors[::-1])): # 计算内外半径 inner_radius = (len(ages) - i - 1) * ring_width outer_radius = inner_radius + ring_width # 获取当前圆环的方向 theta1, theta2 = direction # 创建环形 arc = mpatches.Wedge(center=(0, 0), r=outer_radius, width=ring_width, theta1=theta1, theta2=theta2, facecolor=color, edgecolor='black') # 添加环形到坐标轴 ax.add_patch(arc) # 添加年龄标签 age_angle = -1 age_x = outer_radius * np.cos(np.radians(90 - age_angle))-0.05 age_y = (outer_radius + inner_radius) / 2 * np.sin(np.radians(90 - age_angle)) ax.text(age_x, age_y, age, ha='center', va='center', rotation=age_angle - 90) # 添加占比标签 percent_angle = theta2 percent_x = outer_radius * np.cos(np.radians(90 - percent_angle)) percent_y = outer_radius * np.sin(np.radians(90 - percent_angle)) ax.text(percent_x, percent_y, f'{percent}%', ha='center', va='center', rotation=percent_angle - 90) #在内部画一个比内圈圆半径小的空白圆 inner_circle_radius = (len(ages) - 1) * ring_width smaller_inner_circle = mpatches.Circle((0, 0), inner_circle_radius * 0.15, facecolor='white', edgecolor='none') ax.add_patch(smaller_inner_circle) ax.set_xlim(-1 - outer_radius, 1 + outer_radius) ax.set_ylim(-1 - outer_radius, 1 + outer_radius) # 设置坐标轴属性 ax.set_aspect('equal') ax.axis('off') #plt.savefig('D:/python charm/01/可视化/第二章/图片/玉块图.png') # 显示图形 plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%85%AD/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E7%8E%89%E5%9D%97%E5%9B%BE.png) ###### 3.跑道图 ``` import matplotlib.pyplot as plt import numpy as np import matplotlib.patches as mpatches plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False #年龄分布数据 ages = ['人力部 130', '行政部 226', '财务部 238', '工程部 293', '采购部 326', '销售部 451'] percentages = [12.5, 20.8, 29.2, 37.5, 100, 100] # 假设新增的两个圆环占比为100% #自定义颜色 colors = ['#F7C1CF', '#FFD47F', '#7B92C7', '#ADD9EE', '#E47373', '#73E4C7'] #创建图形和坐标轴 fig, ax = plt.subplots(figsize=(10, 10)) #设置环形宽度 ring_width = 0.1 #定义每个圆环的方向 directions = [(10, 90), (-10, 90), (-30, 90), (-50, 90), (-70, 90), (-90, 90)] #绘制每个年龄段的环形 for i, (age, percent, direction, color) in enumerate(zip(ages[::-1], percentages[::-1], directions[::-1], colors[::-1])): #计算内外半径 inner_radius = (len(ages) - i - 1) * ring_width outer_radius = inner_radius + ring_width #获取当前圆环的方向 theta1, theta2 = direction #创建环形 arc = mpatches.Wedge(center=(0, 0), r=outer_radius, width=ring_width, theta1=theta1, theta2=theta2, facecolor=color, edgecolor='black') # 添加环形到坐标轴 ax.add_patch(arc) # 添加年龄标签 age_x = outer_radius * np.cos(np.radians(90))-0.15 age_y = (outer_radius + inner_radius) / 2 ax.text(age_x, age_y, age, ha='center', va='center', rotation=0) #在内部画一个比内圈圆半径小的空白圆 inner_circle_radius = (len(ages) - 1) * ring_width smaller_inner_circle = mpatches.Circle((0, 0), inner_circle_radius * 0.07, facecolor='white', edgecolor='none') ax.add_patch(smaller_inner_circle) # 设置坐标轴界限,使图形居中 ax.set_xlim(-1 - outer_radius, 1 + outer_radius) ax.set_ylim(-1 - outer_radius, 1 + outer_radius) # 设置坐标轴属性 ax.set_aspect('equal') ax.axis('off') #plt.savefig('D:/python charm/01/可视化/第二章/图片/跑道图.png') # 显示图形 plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%85%AD/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E8%B7%91%E9%81%93%E5%9B%BE.png) ##### 七、南丁格尔圆环图、仪表盘图、目标柱形图、子弹图 ###### 1.南丁格尔圆环图 ``` from pyecharts import options as opts from pyecharts.charts import Pie ages = ['>=50', '[40,50)', '[30,40)', '[20,30)'] percentages = [12.5, 20.8, 29.2, 37.5] colors = ["#C3E2EC", "#CECCE5", "#F7C4C1", "#BCD1BC"] pie = ( Pie(init_opts=opts.InitOpts(width="800px", height="600px")) .add( series_name="年龄分布", data_pair=[(age, percentage) for age, percentage in zip(ages, percentages)], radius=["40%", "70%"], rosetype="radius", color=colors, ) .set_global_opts( title_opts=opts.TitleOpts(title="年龄分布图"), legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"), ) .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)")) ) # 显示图表 pie.render("D:/python charm/01/可视化/第二章/图片/南丁格尔圆环图.html") ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%B8%83/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-11-21%20212902.png) ###### 2.仪表盘图 ``` import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False inner_radius = 0.9 outer_radius = 1 num_segments = 14 inner_colors = ['#F7C1D0', '#F7C1D0', '#ADD9EE', '#ADD9EE', '#ADD9EE', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#FFFFFF', '#CAC0E1', '#CAC0E1', '#CAC0E1', '#F7C1DB', '#F7C1DC'] outer_colors = ['#FFD47E' for _ in range(num_segments)] fig, ax = plt.subplots() wedges1, texts1 = ax.pie([1] * num_segments, radius=inner_radius, colors=inner_colors, startangle=90, counterclock=False, wedgeprops=dict(width=0.3, edgecolor='w')) wedges2, texts2 = ax.pie([1] * num_segments, radius=outer_radius, colors=outer_colors, startangle=90, counterclock=False, wedgeprops=dict(width=0.3, edgecolor='w')) labels = [] label_value = 70 for color in inner_colors: if color != '#FFFFFF': labels.append(label_value) label_value += 10 else: labels.append(None) for i, wedge in enumerate(wedges1): if labels[i] is not None: angle = (wedge.theta2 - wedge.theta1) / 2 + wedge.theta1 x_left = (inner_radius - 0.05) * np.cos(np.deg2rad(angle - 5)) y_left = (inner_radius + 0.05) * np.sin(np.deg2rad(angle - 5)) x_right = (inner_radius + 0.05) * np.cos(np.deg2rad(angle + 5)) y_right = (inner_radius + 0.05) * np.sin(np.deg2rad(angle + 5)) ax.text(x_left, y_left, str(labels[i]), ha='center', va='center', color='black') ax.text(x_right, y_right, str(labels[i]), ha='center', va='center', color='black') ax.set_aspect('equal') plt.title('仪表盘图') #plt.savefig('D:/python charm/01/可视化/第二章/图片/仪表盘图.png') # 显示图表 plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%B8%83/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E4%BB%AA%E8%A1%A8%E7%9B%98%E5%9B%BE.png) ###### 3.目标柱形图 ``` import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False products = ['口红', '面膜', '隔离', '防晒', '精华', '面霜'] target_sales = [700, 500, 600, 900, 600, 600] actual_sales = [653, 523, 648, 856, 714, 785] #创建柱状图 plt.figure(figsize=(12, 6)) #目标销量柱状图 plt.bar(products, target_sales, color='none', edgecolor='black', width=0.6, label='目标销量') #实际销量柱状图,宽度小一些,蓝色填充,白色外框 actual_bars = plt.bar(products, actual_sales, color='skyblue', edgecolor='white', width=0.4, label='实际销量') #在每个柱状图上方加上实际销量的标签 for bar in actual_bars: yval = bar.get_height() plt.text(bar.get_x() + bar.get_width()/2, yval, int(yval), va='bottom', ha='center', color='black') # 添加标题和标签 plt.title('目标销量与实际销量柱状图') plt.xlabel('商品') plt.ylabel('销量') plt.legend() # 隐藏y轴的刻度线 plt.gca().yaxis.set_major_locator(plt.NullLocator()) #plt.savefig('D:/python charm/01/可视化/第二章/图片/目标柱形图.png') # 显示图表 plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%B8%83/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E7%9B%AE%E6%A0%87%E6%9F%B1%E5%BD%A2%E5%9B%BE.png) ###### 4.子弹图 ``` import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False categories = ['口红', '面膜', '隔离', '防晒', '精华', '面霜'] targets = [700, 500, 600, 900, 600, 600] passing_scores = [600] * len(categories) good_scores = [200] * len(categories) actual_scores = [653, 523, 648, 856, 714, 785] #堆叠柱状图 bar_width = 0.5 index = np.arange(len(categories)) #目标、及格、良好分数的柱状图 plt.bar(index, targets, bar_width, label='目标', color='#F7C4C1') plt.bar(index, passing_scores, bar_width, bottom=targets, label='及格', color='#DBEDC5') plt.bar(index, good_scores, bar_width, bottom=[i+j for i,j in zip(targets, passing_scores)], label='良好', color='#C3E2EC') #实际分数的柱状图 plt.bar(index, actual_scores, bar_width, label='实际', color='#7A10B5') #目标的横线,颜色用红色 plt.hlines(targets, index - bar_width/2, index + bar_width/2, colors='red', linestyles='-', label='目标线') plt.xlabel('商品') plt.ylabel('分数') plt.title('目标、及格、良好与实际分数柱状图') plt.xticks(index, categories) plt.legend() #plt.savefig('D:/python charm/01/可视化/第二章/图片/子弹图.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%B8%83/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%AD%90%E5%BC%B9%E5%9B%BE.png) ##### 八、柱形图、簇状柱形折线图、复合柱形图、滑珠图、对比滑珠图 ###### 1.柱形图 ``` import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False regions = ['华北', '华南', '东北', '西北', '西南', '华东'] sales = [2354, 1902, 3524, 2698, 2896, 2563] growth_rates = [12, 25, 16, 21, 18, 25] plt.figure(figsize=(10, 6)) bars = plt.bar(regions, sales, color='skyblue') for bar in bars: height = bar.get_height() plt.text(bar.get_x() + bar.get_width() / 2., height, f'{height}', ha='center', va='bottom', fontsize=10) for i, rate in enumerate(growth_rates): plt.scatter(i, sales[i] + 500, color='red', s=400) plt.text(i, sales[i] + 500, f'{rate}%', ha='center', va='center', color='white', fontsize=10) plt.title('各区域销量及同比去年增长率') plt.xlabel('区域') plt.ylabel('销量') #plt.savefig('D:/python charm/01/可视化/第二章/图片/柱形图.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%85%AB/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E6%9F%B1%E5%BD%A2%E5%9B%BE.png) ###### 2.簇状柱形折线图 ``` import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False regions = ['华北', '华南', '东北', '西北', '西南', '华东'] sales_2022 = [2354, 1902, 3524, 2698, 2896, 2563] sales_2021 = [2021, 1563, 3213, 2531, 2631, 2361] growth_rate = [16, 22, 10, 7, 10, 9] bar_width = 0.35 index = np.arange(len(regions)) fig, ax1 = plt.subplots(figsize=(10, 6)) bar1 = ax1.bar(index - bar_width/2, sales_2022, bar_width, label='2022年销量', color='#CECCE5') bar2 = ax1.bar(index + bar_width/2, sales_2021, bar_width, label='2021年销量', color='#C3E2EC') for i in range(len(sales_2022)): ax1.text(i - bar_width/2, sales_2022[i] + 50, str(sales_2022[i]), ha='center', va='bottom', color='black') ax1.text(i + bar_width/2, sales_2021[i] + 50, str(sales_2021[i]), ha='center', va='bottom', color='black') ax2 = ax1.twinx() line3 = ax2.plot(index, growth_rate, color='#e74c3c', marker='o', linestyle='-', linewidth=2, label='同比增长率') ax2.set_ylim(0, max(growth_rate) * 1.5) for i in range(len(growth_rate)): ax2.text(i, growth_rate[i] + 0.005, f'{growth_rate[i]}%', ha='center', va='bottom', color='black') ax1.set_xlabel('区域') ax1.set_ylabel('销量(单位:件)') ax2.set_ylabel('同比增长率 (%)') ax1.set_title('2022 vs 2021 销量对比及同比增长率') ax1.set_xticks(index) ax1.set_xticklabels(regions) ax1.legend(loc='upper left') ax2.legend(loc='upper right') plt.tight_layout() #plt.savefig('D:/python charm/01/可视化/第二章/图片/簇状柱形折线图.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%85%AB/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E7%B0%87%E7%8A%B6%E6%9F%B1%E5%BD%A2%E6%8A%98%E7%BA%BF%E5%9B%BE.png) ###### 3.复合柱形图 ``` import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False months = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"] monthly_sales = [2354, 1902, 3524, 2698, 2896, 2563, 3156, 2896, 3621, 2635, 2963, 2789] quarterly_sales = [7780, 7780, 7780, 8157, 8157, 8157, 9673, 9673, 9673, 8387, 8387, 8387] x_groups = [0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14] group_labels = ["Q1", "Q2", "Q3", "Q4"] quarter_colors = ['#4a4a8c', '#8c4a4a', '#4a8c4a', '#8c4a8c'] fig, ax = plt.subplots(figsize=(12, 7)) bar_width = 0.4 spacing = 1.5 for i, (x, sale) in enumerate(zip(x_groups, monthly_sales)): ax.bar(x, sale, width=bar_width, color=['#6a87ff', '#6a87ff', '#6a87ff', '#ff8b4b', '#ff8b4b', '#ff8b4b', '#a87332', '#a87332', '#a87332', '#b84d9b', '#b84d9b', '#b84d9b'][i]) ax.text(x, sale + 100, str(sale), ha='center', va='bottom', color='white', fontsize=10) for i in range(0, len(x_groups), 3): group_x = np.mean(x_groups[i:i+3]) ax.bar(group_x, quarterly_sales[i], width=bar_width * 3 + spacing, color=quarter_colors[i // 3], alpha=0.6) ax.text(group_x, quarterly_sales[i] + 200, str(quarterly_sales[i]), ha='center', va='bottom', color='black', fontsize=12) ax.set_xticks([np.mean(x_groups[i:i+3]) for i in range(0, len(x_groups), 3)]) ax.set_xticklabels(group_labels) ax.set_xlabel('季度') ax.set_ylabel('销量') ax.set_title('2021年各月化妆品销量走势\n2021年第三季度销量最多9673,9月单月销量最大3621') plt.figtext(0.1, -0.05, '*注:数据源于公司销售系统,统计日期截至2021.12.31', ha="left", fontsize=10, color="grey") plt.tight_layout() #plt.savefig('D:/python charm/01/可视化/第二章/图片/复合柱形图.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%85%AB/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%A4%8D%E5%90%88%E6%9F%B1%E5%BD%A2%E5%9B%BE.png) ###### 4.滑珠图 ``` import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False regions = ['华东', '西北', '东北', '华北', '华南'] completion_rates = [35, 51, 62, 74, 86] not_completion_rates = [65, 49, 38, 26, 14] colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99', '#c2c2f0'] fig, ax = plt.subplots(figsize=(10, 6)) for i in range(len(regions)): ax.barh(i, completion_rates[i], color=colors[i], edgecolor='white', height=0.4) ax.barh(i, not_completion_rates[i], left=completion_rates[i], color='lightgray', edgecolor='white', height=0.4) ax.plot(completion_rates[i], i, 'o', markersize=40, color=colors[i], markeredgewidth=2, markeredgecolor='white') ax.text(completion_rates[i], i, f"{completion_rates[i]}%", va='center', ha='center', color='white', fontsize=20, fontweight='bold') ax.set_xlabel('百分比 (%)') ax.set_title('2022年上半年产品销量目标达成率情况\n华南完成率最高达到86%,华东最低35%') ax.set_yticks(range(len(regions))) ax.set_yticklabels(regions) ax.invert_yaxis() plt.figtext(0.1, -0.05, '*注:数据源于公司销售系统,统计日期截至2022.06.30', ha="left", fontsize=10, color="grey") plt.xlim(0, 100) plt.grid(axis='x', linestyle='--', alpha=0.7) #plt.savefig('D:/python charm/01/可视化/第二章/图片/滑珠图.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%85%AB/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E6%BB%91%E7%8F%A0%E5%9B%BE.png) ###### 5.对比滑珠图 ``` import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False regions = ["华南", "华北", "东北", "西北", "华东"] completion_2022 = [86, 74, 62, 51, 35] completion_2021 = [92, 69, 53, 39, 45] fig, ax = plt.subplots(figsize=(10, 6)) ax.set_title("2022年上半年销量目标达成率与2021年对比") ax.set_xlabel("完成率 (%)") ax.set_yticks(range(len(regions))) ax.set_yticklabels(regions) ax.invert_yaxis() bar_height = 0.2 for i in range(len(regions)): ax.barh(i, 100, height=bar_height, color='lightgreen', alpha=0.6) ax.barh(i, completion_2022[i], height=bar_height, color='skyblue', alpha=0.7) ax.scatter(completion_2021, range(len(regions)), s=400, color='red', alpha=0.9, label="2021完成率") ax.scatter(completion_2022, range(len(regions)), s=400, color='blue', alpha=0.9, label="2022完成率") for i, comp_2022 in enumerate(completion_2022): ax.text(comp_2022, i + 0.3, f"{comp_2022}%", va='bottom', ha='center', color='skyblue', fontweight='bold') for i, comp_2021 in enumerate(completion_2021): ax.text(comp_2021, i + 0.3, f"{comp_2021}%", va='bottom', ha='center', color='skyblue', fontweight='bold') ax.legend() plt.grid(axis='x', linestyle='--', alpha=0.6) #plt.savefig('D:/python charm/01/可视化/第二章/图片/对比滑珠图.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%85%AB/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%AF%B9%E6%AF%94%E6%BB%91%E7%8F%A0%E5%9B%BE.png) ##### 九、人力资源数据静态大屏设计 ``` import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False #创建图形和子图 fig, axes = plt.subplots(2, 3, figsize=(18, 8), dpi=100) fig.patch.set_facecolor('#2C3E50') #年龄环形图 ax = axes[0, 0] labels = ['18-24', '25-29', '30-34', '35-39', '40=以上'] sizes = [7, 16, 22, 20, 35] colors = ['#5DADE2', '#F39C12', '#2ECC71', '#F4D03F', '#2874A6'] wedges, texts, autotexts = ax.pie( sizes, labels=None, colors=colors, autopct='%1.0f%%', startangle=90, pctdistance=0.75 ) centre_circle = plt.Circle((0, 0), 0.60, fc='#2C3E50') ax.add_artist(centre_circle) ax.set_title('年龄', fontsize=16, color='white', pad=10) ax.set_facecolor('#2C3E50') for autotext in autotexts: autotext.set_color('white') legend = ax.legend( wedges, labels, loc="center left", bbox_to_anchor=(1, 0, 0.5, 1), fontsize=10 ) legend.get_frame().set_facecolor('#2C3E50') legend.get_frame().set_edgecolor('white') plt.setp(legend.get_texts(), color='white') #性别环形图 ax = axes[0, 1] labels = ['男', '女'] sizes = [60, 40] colors = ['#F39C12', '#5DADE2'] wedges, texts, autotexts = ax.pie( sizes, labels=None, colors=colors, autopct='%1.0f%%', startangle=90, pctdistance=0.75 ) centre_circle = plt.Circle((0, 0), 0.60, fc='#2C3E50') ax.add_artist(centre_circle) ax.set_title('性别', fontsize=16, color='white', pad=10) ax.set_facecolor('#2C3E50') for autotext in autotexts: autotext.set_color('white') legend = ax.legend( wedges, labels, loc="center left", bbox_to_anchor=(1, 0, 0.5, 1), fontsize=10 ) legend.get_frame().set_facecolor('#2C3E50') legend.get_frame().set_edgecolor('white') plt.setp(legend.get_texts(), color='white') #婚姻状况环形图 ax = axes[0, 2] labels = ['单身', '已婚', '离异'] sizes = [32, 46, 22] colors = ['#F39C12', '#2874A6', '#5DADE2'] wedges, texts, autotexts = ax.pie( sizes, labels=None, colors=colors, autopct='%1.0f%%', startangle=90, pctdistance=0.75 ) centre_circle = plt.Circle((0, 0), 0.60, fc='#2C3E50') ax.add_artist(centre_circle) ax.set_title('婚姻状况', fontsize=16, color='white', pad=10) ax.set_facecolor('#2C3E50') for autotext in autotexts: autotext.set_color('white') legend = ax.legend( wedges, labels, loc="center left", bbox_to_anchor=(1, 0, 0.5, 1), fontsize=10 ) legend.get_frame().set_facecolor('#2C3E50') legend.get_frame().set_edgecolor('white') plt.setp(legend.get_texts(), color='white') #学历 ax = axes[1, 0] labels = ['博士研究生', '硕士研究生', '本科', '专科', '专科以下'] values = [48, 398, 572, 170, 282] bars = ax.barh(labels, values, color='#5DADE2') ax.set_title('学历', fontsize=16, color='white', pad=10) ax.tick_params(axis='y', colors='white') ax.xaxis.set_visible(False) for bar in bars: ax.text(bar.get_width() + 5, bar.get_y() + bar.get_height() / 2, f'{int(bar.get_width())}', va='center', color='white') ax.set_facecolor('#2C3E50') #入转调 ax = axes[1, 1] labels = ['入职', '转入', '转出'] values = [40, 5, 5] bars = ax.bar(labels, values, color='#5DADE2', width=0.5) ax.text(1, max(values) + 10, '总人数: 147', fontsize=14, color='white', ha='center') ax.set_title('入转调', fontsize=16, color='white', pad=10) ax.tick_params(axis='x', colors='white') ax.tick_params(axis='y', left=False, labelleft=False) ax.set_facecolor('#2C3E50') for bar in bars: ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 1, f'{int(bar.get_height())}', ha='center', color='white') #部门 ax = axes[1, 2] labels = ['财务部', '人力资源部', '行政部', '信息技术部', '研发部', '销售部'] values = [17, 46, 9, 162, 799, 437] bars = ax.barh(labels, values, color='#5DADE2') ax.set_title('部门', fontsize=16, color='white', pad=10) ax.tick_params(axis='y', colors='white') ax.tick_params(axis='x', length=0, labelbottom=False) ax.invert_yaxis() ax.set_facecolor('#2C3E50') for bar in bars: ax.text(bar.get_width() + 10, bar.get_y() + bar.get_height() / 2, f'{int(bar.get_width())}', va='center', color='white') plt.suptitle('公司人员结构看板', fontsize=20, color='white', y=0.95) plt.tight_layout(rect=[0, 0, 1, 0.95]) plt.savefig('D:/python charm/01/可视化/人力资源静态数据大屏设计/图片.png', dpi=300, bbox_inches='tight') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E4%B9%9D%EF%BC%88%E4%BA%BA%E5%8A%9B%E8%B5%84%E6%BA%90%E6%95%B0%E6%8D%AE%E9%9D%99%E6%80%81%E5%A4%A7%E5%B1%8F%E8%AE%BE%E8%AE%A1%EF%BC%89/%E5%9B%BE%E7%89%87.png) ##### 十、销售看板 ###### 1.划分销售数据 ``` import os import pandas as pd file_path = r"D:\python charm\01\可视化\销售看板参考\第四章 销售看板参考.xlsx" excel_file = pd.ExcelFile(file_path) print(f"文件包含的工作表:{excel_file.sheet_names}") sheet_name = "销售明细" if sheet_name not in excel_file.sheet_names: print(f"工作表 '{sheet_name}' 不存在,请选择以下之一:{excel_file.sheet_names}") raise ValueError("指定的工作表不存在") data = pd.read_excel(file_path, sheet_name=sheet_name) data['订单日期'] = pd.to_datetime(data['订单日期'], errors='coerce') # 目标目录 output_dir = r"D:\python charm\01\可视化\销售看板参考" for month in range(1, 13): df_month = data[data['订单日期'].dt.month == month] file_name = os.path.join(output_dir, f"销售明细_{month}.xlsx") df_month.to_excel(file_name, index=False) print(f"已导出 {file_name}") ``` ###### 2.划分成本数据 ``` import os import pandas as pd file_path = r"D:\python charm\01\可视化\销售看板参考\第四章 销售看板参考.xlsx" sheet_name = "成本明细" data = pd.read_excel(file_path, sheet_name=sheet_name) monthly_data = {} for month in range(1, 13): month_str = f"{month}月" monthly_data[f'dh{month}'] = data[data['月份_成本'] == month_str] # 目标目录 output_dir = r"D:\python charm\01\可视化\销售看板参考" for name, df in monthly_data.items(): file_name = os.path.join(output_dir, f"成本明细_{name}.xlsx") df.to_excel(file_name, index=False) print(f"已导出 {file_name}") ``` ###### 3.产品销量 ``` import matplotlib.pyplot as plt import numpy as np import pandas as pd plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False file_path = r"D:\python charm\01\可视化\销售看板参考\销售明细_12.xlsx" data = pd.read_excel(file_path) data = data['产品类别'].value_counts() # 设置图表颜色和标签 labels = data.index sizes = data.values colors = ['#FF6F91', '#FF9671', '#FFC75F'] # 自定义百分比显示函数 def custom_autopct(pct): value = pct * sum(sizes) / 100 if round(value * 10) % 10 >= 6: return f"{round(pct)}%" else: return f"{np.floor(pct)}%" # 绘制圆环图 plt.figure(figsize=(10, 10)) ax = plt.gca() ax.set_facecolor('#2E4057') plt.gcf().set_facecolor('#2E4057') wedges, texts, autotexts = plt.pie( sizes, labels=labels, autopct=custom_autopct, startangle=90, colors=colors, wedgeprops={'width': 0.4, 'edgecolor': '#2E4057', 'linewidth': 1}, textprops={'fontsize': 20, 'color': 'white'} ) # 调整百分比的字体大小 for autotext in autotexts: autotext.set_fontsize(30) autotext.set_color('white') # 添加中心的总销量信息 total_sales = sum(sizes) plt.text(0, 0, f"{total_sales}\n总销", ha='center', va='center', fontsize=30, weight='bold', color='white') # 添加图例 plt.legend( wedges, labels, loc="center right", fontsize=12, frameon=False, labelcolor='white', bbox_to_anchor=(1.2, 0.5) ) # 设置标题 plt.title('产品类别销量', fontsize=20, color='white') # 调整布局避免重叠 plt.tight_layout() plt.savefig(r'D:\python charm\01\可视化\销售看板参考\图片\产品销量.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%8D%81%EF%BC%88%E9%94%80%E5%94%AE%E7%9C%8B%E6%9D%BF%E5%8F%82%E8%80%83%EF%BC%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E4%BA%A7%E5%93%81%E9%94%80%E9%87%8F.png) ###### 4.利润率 ``` import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False sales = 146.87 # 销售额 (万) profit = 14.27 # 利润额 (万) profit_rate = (profit / sales) * 100 # 利润率计算 # 创建图表 plt.figure(figsize=(6, 6), facecolor='#2E4057') ax = plt.gca() ax.set_facecolor('#2E4057') # 绘制圆环图 colors = ['#FF6F91', '#D9D9D9'] plt.pie( [profit_rate, 100 - profit_rate], radius=1, colors=colors, startangle=--47, wedgeprops={'width': 0.3, 'edgecolor': '#2E4057'} ) # 中心文本 plt.text(0, 0.15, f"{profit_rate:.2f}%", ha='center', va='center', fontsize=24, color='white', weight='bold') plt.text(0, -0.1, "利润率", ha='center', va='center', fontsize=20, color='white') # 右侧文本信息 plt.text(1.2, 0.3, f"利润额(万) {profit:.2f}", ha='left', va='center', fontsize=20, color='#FF6F91') plt.text(1.2, 0.0, f"销售额(万) {sales:.2f}", ha='left', va='center', fontsize=20, color='#FF6F91') plt.text(1.2, 0.15, "/", ha='left', va='center', fontsize=20, color='white') # 底部按钮样式文本 plt.text(0, -1.3, "利润额占比销售额", ha='center', va='center', fontsize=20, color='white', bbox=dict(facecolor='#2E4057', edgecolor='#4F81BD', boxstyle='round,pad=0.4', linewidth=2)) # 隐藏多余轴 ax.axis('equal') # 调整布局 plt.tight_layout() plt.savefig(r'D:\python charm\01\可视化\销售看板参考\图片\利润率.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%8D%81%EF%BC%88%E9%94%80%E5%94%AE%E7%9C%8B%E6%9D%BF%E5%8F%82%E8%80%83%EF%BC%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%88%A9%E6%B6%A6%E7%8E%87.png) ###### 5.各区域销量 ``` import pandas as pd import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False file_path = r"D:\python charm\01\可视化\销售看板参考\销售明细_12.xlsx" df12 = pd.read_excel(file_path) # 统计各区域数量 region_counts = df12['区域'].value_counts() # 指定区域的顺序 region_order = ['华北', '华南', '东北', '西北', '西南', '华东'] region_counts = region_counts.reindex(region_order) # 创建图表 plt.figure(figsize=(8, 4), facecolor='#2E4057') ax = plt.gca() ax.set_facecolor('#2E4057') # 绘制柱状图 bars = plt.bar(region_counts.index, region_counts.values, color='#6DCFF6', width=0.6) # 添加数据标签 for bar in bars: plt.text( bar.get_x() + bar.get_width() / 2, bar.get_height() + 1, f"{int(bar.get_height())}", ha='center', va='bottom', fontsize=20, color='white' ) # 设置标题和标签 plt.title("区域销量", fontsize=20, color='white', pad=20) plt.xticks(fontsize=22, color='white') plt.yticks([]) plt.tick_params(axis='x', which='both', length=0) # 隐藏图表边框 for spine in ax.spines.values(): spine.set_visible(False) # 调整布局 plt.tight_layout() plt.savefig(r'D:\python charm\01\可视化\销售看板参考\图片\各区域销量.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%8D%81%EF%BC%88%E9%94%80%E5%94%AE%E7%9C%8B%E6%9D%BF%E5%8F%82%E8%80%83%EF%BC%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%90%84%E5%8C%BA%E5%9F%9F%E9%94%80%E9%87%8F.png) ###### 6.各快递公司销量 ``` import pandas as pd import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False file_path = r"D:\python charm\01\可视化\销售看板参考\销售明细_12.xlsx" df12 = pd.read_excel(file_path) dfkd1 = ( df12.groupby(['快递公司']) .size() .reset_index(name='数量') ) # 设置图表风格 plt.figure(figsize=(8, 5), facecolor='#2E4057') ax = plt.gca() ax.set_facecolor('#2E4057') #反转数据顺序 dfkd1 = dfkd1.iloc[::-1] # 绘制柱状图 bars = plt.bar(dfkd1['快递公司'], dfkd1['数量'], color='#FF6F91', width=0.5) # 添加数据标签 for bar in bars: plt.text( bar.get_x() + bar.get_width() / 2, bar.get_height() + 5, f"{int(bar.get_height())}", ha='center', va='bottom', fontsize=20, color='white' ) # 设置标题和标签 plt.title("快递公司销量", fontsize=20, color='white', pad=20) plt.xticks(fontsize=18, color='white') plt.yticks([]) plt.tick_params(axis='x', which='both', length=0) # 隐藏图表边框 for spine in ax.spines.values(): spine.set_visible(False) plt.tight_layout() plt.savefig(r'D:\python charm\01\可视化\销售看板参考\图片\各快递公司销量.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%8D%81%EF%BC%88%E9%94%80%E5%94%AE%E7%9C%8B%E6%9D%BF%E5%8F%82%E8%80%83%EF%BC%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%90%84%E5%BF%AB%E9%80%92%E5%85%AC%E5%8F%B8%E9%94%80%E9%87%8F.png) ###### 7.各月销售额 ``` import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False months = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"] sales = [145.22, 118.63, 131.27, 124.26, 116.51, 108.11, 121.62, 111.74, 134.29, 137.28, 119.55, 146.87] plt.figure(figsize=(10, 6), facecolor='#2E4057') ax = plt.gca() ax.set_facecolor('#2E4057') # 绘制折线图 plt.plot(months, sales, color='#4F81BD', marker='o', linewidth=2) # 填充区域 plt.fill_between(months, sales, color='#4F81BD', alpha=0.5) plt.title("各月销售额(万)", fontsize=22, color='white', pad=20) plt.xticks(fontsize=20, color='white') plt.yticks(fontsize=20, color='white') plt.ylabel("销售额(万)", fontsize=20, color='white') plt.xlabel("月份", fontsize=20, color='white') # 隐藏边框 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) #调整 y 轴范围 plt.ylim(0, 200) #添加网格线 plt.grid(axis='y', color='gray', linestyle='--', linewidth=0.5, alpha=0.5) #调整布局 plt.tight_layout() plt.savefig(r'D:\python charm\01\可视化\销售看板参考\图片\各月销售额.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%8D%81%EF%BC%88%E9%94%80%E5%94%AE%E7%9C%8B%E6%9D%BF%E5%8F%82%E8%80%83%EF%BC%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E5%90%84%E6%9C%88%E9%94%80%E5%94%AE%E9%A2%9D.png) ###### 8.成本 ``` import matplotlib.pyplot as plt import numpy as np import pandas as pd plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False file_path = r"D:\python charm\01\可视化\销售看板参考\成本明细_dh12.xlsx" dh12 = pd.read_excel(file_path) # 总成本 total_cost = dh12['成本'].sum() # 准备数据 categories = dh12['类别'] costs = dh12['成本'] percentages = (costs / total_cost) * 100 # 设置图表风格 plt.figure(figsize=(10, 10), facecolor='#2E4057') # 子图参数 colors = ['#4F81BD', '#C0504D', '#9BBB59', '#8064A2'] rows, cols = 2, 2 # 2x2 布局 # 绘制每个类别的圆环图 for i, (category, cost, percentage) in enumerate(zip(categories, costs, percentages)): ax = plt.subplot(rows, cols, i + 1) ax.set_facecolor('#2E4057') # 绘制圆环图 wedges, texts = ax.pie( [percentage, 100 - percentage], radius=1, colors=[colors[i], '#D9D9D9'], # 当前类别颜色和灰色背景 startangle=90, # 设置起始角度为 -45 度 wedgeprops={'width': 0.3, 'edgecolor': 'white'} ) # 中心文本 ax.text(0, 0.1, f"{percentage:.2f}%", ha='center', va='center', fontsize=24, color='white') ax.text(0, -0.3, f"{category}\n用合计", ha='center', va='center', fontsize=20, color='white') ax.text(0, -0.6, f"{cost:.2f}", ha='center', va='center', fontsize=20, color='white') # 设置标题 ax.set_title(category, fontsize=20, color='white', pad=10) # 整体标题 plt.suptitle("成本费用", fontsize=20, color='white', y=0.95) # 调整布局 plt.tight_layout(rect=[0, 0, 1, 0.93]) plt.savefig(r'D:\python charm\01\可视化\销售看板参考\图片\成本.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%8D%81%EF%BC%88%E9%94%80%E5%94%AE%E7%9C%8B%E6%9D%BF%E5%8F%82%E8%80%83%EF%BC%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E6%88%90%E6%9C%AC.png) ###### 9.月同比增长 ``` import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False months = ["11月", "12月"] sales = [664, 727] change_rate = 9.49 # 颜色设置 colors = ['#4F81BD', '#6DCFF6'] # 创建图表 plt.figure(figsize=(8, 4), facecolor='#2E4057') ax = plt.gca() ax.set_facecolor('#2E4057') # 绘制水平条形图 bars = plt.barh(months, sales, color=colors, height=0.4, edgecolor='none') # 添加数值标签 for i, bar in enumerate(bars): # 条形图右侧显示销售值 plt.text(bar.get_width() + 10, bar.get_y() + bar.get_height() / 2, f"{sales[i]}", va='center', ha='left', fontsize=22, color='white') # 显示变化率文本 plt.text(max(sales) + 100, bars[1].get_y() + bars[1].get_height() / 2, f"{change_rate:.2f}%", ha='left', va='center', fontsize=22, color='white', weight='bold') plt.text(max(sales) + 100, bars[0].get_y() + bars[0].get_height() / 2, "同比", ha='left', va='center', fontsize=22, color='white') # 设置标题 plt.title("销量环比", fontsize=20, color='white', pad=20) # 设置左侧月份字体大小 plt.yticks(fontsize=25, color='white') # 隐藏坐标轴 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.tick_params(left=False, bottom=False, labelleft=True, labelbottom=False) # 调整布局 plt.tight_layout() plt.savefig(r'D:\python charm\01\可视化\销售看板参考\图片\月同比增长.png') plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%8D%81%EF%BC%88%E9%94%80%E5%94%AE%E7%9C%8B%E6%9D%BF%E5%8F%82%E8%80%83%EF%BC%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E6%9C%88%E5%90%8C%E6%AF%94%E5%A2%9E%E9%95%BF.png) ###### 10.看板 ``` import matplotlib.pyplot as plt import matplotlib.image as mpimg plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False image_positions = { "part1": [ {"path": r"D:\python charm\01\可视化\销售看板参考/图片/产品销量.png", "pos": [0.05, 0.55, 0.4, 0.3]}, {"path": r"D:\python charm\01\可视化\销售看板参考/图片/成本.png", "pos": [0.05, 0.1, 0.49, 0.40]}, ], "part2": [ {"path": r"D:\python charm\01\可视化\销售看板参考/图片/月同比增长.png", "pos": [0.30, 0.60, 0.42, 0.22]}, {"path": r"D:\python charm\01\可视化\销售看板参考/图片/利润率.png", "pos": [0.30, 0.10, 0.5, 0.40]}, ], "part3": [ {"path": r"D:\python charm\01\可视化\销售看板参考/图片/各月销售额.png", "pos": [0.65, 0.6, 0.30, 0.25]}, {"path": r"D:\python charm\01\可视化\销售看板参考/图片/各区域销量.png", "pos": [0.65, 0.37, 0.25, 0.2]}, {"path": r"D:\python charm\01\可视化\销售看板参考/图片/各快递公司销量.png", "pos": [0.65, 0.11, 0.25, 0.2]}, ], } # 创建主布局 fig = plt.figure(figsize=(40, 15), facecolor="#2E4057") # 绘制每张图片 for part, images in image_positions.items(): for image_info in images: ax = fig.add_axes(image_info["pos"]) img = mpimg.imread(image_info["path"]) ax.imshow(img) ax.axis("off") # 添加主标题 fig.suptitle("公司销售数据可视化看板", fontsize=40, color="white", y=0.95) plt.savefig(r'D:\python charm\01\可视化\销售看板参考\图片\看板.png') # 显示图表 plt.show() ``` ![输入图片说明](%E5%AE%9E%E9%AA%8C%E5%8D%81%EF%BC%88%E9%94%80%E5%94%AE%E7%9C%8B%E6%9D%BF%E5%8F%82%E8%80%83%EF%BC%89/%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C/%E7%9C%8B%E6%9D%BF.png)