Python数据可视化科技图表绘制系列教程(二)

发布时间:2026/8/19 17:12:56
Python数据可视化科技图表绘制系列教程(二) 目录表格风格图使用Seaborn函数绘图设置图表风格设置颜色主题图表分面绘图过程使用绘图函数绘图定义主题分面1分面2【声明】未经版权人书面许可任何单位或个人不得以任何形式复制、发行、出租、改编、汇编、传播、展示或利用本博客的全部或部分内容也不得在未经版权人授权的情况下将本博客用于任何商业目的。但版权人允许个人学习、研究、欣赏等非商业性用途的复制和传播。非常推荐大家学习《Python数据可视化科技图表绘制》这本书籍。表格风格图import matplotlib.pyplot as plt import numpy as np import matplotlib.colors as mcolors from matplotlib.patches import Rectangle np.random.seed(19781101) # 固定随机种子以便结果可复现 def plot_scatter(ax,prng,nb_samples100): 绘制散点图 for mu,sigma,marker in [(-.5,0.75,o),(0.75,1.,s)]: x,yprng.normal(locmu,scalesigma,size(2,nb_samples)) ax.plot(x,y,lsnone,markermarker) ax.set_xlabel(X-label) ax.set_title(Axes title) return ax def plot_colored_lines(ax): 绘制颜色循环线条 tnp.linspace(-10,10,100) def sigmoid(t,t0): return 1/(1np.exp(-(t-t0))) nb_colorslen(plt.rcParams[axes.prop_cycle]) shiftsnp.linspace(-5,5,nb_colors) amplitudesnp.linspace(1,1.5,nb_colors) for t0,a in zip(shifts,amplitudes): ax.plot(t,a*sigmoid(t,t0),-) ax.set_xlim(-10,10) return ax def plot_bar_graphs(ax,prng,min_value5,max_value25,nb_samples5): 绘制两个并排的柱状图。 xnp.arange(nb_samples) ya,ybprng.randint(min_value,max_value,size(2,nb_samples)) width0.25 ax.bar(x,ya,width) ax.bar(xwidth,yb,width,colorC2) ax.set_xticks(xwidth,labels[a,b,c,d,e]) return ax def plot_colored_circles(ax,prng,nb_samples15): 绘制彩色圆形。 for sty_dict,j in zip(plt.rcParams[axes.prop_cycle](), range(nb_samples)): ax.add_patch(plt.Circle(prng.normal(scale3,size2), radius1.0,colorsty_dict[color])) ax.grid(visibleTrue) # 添加标题以启用网格 plt.title(ax.grid(True),familymonospace,fontsizesmall) ax.set_xlim([-4,8]) ax.set_ylim([-5,6]) ax.set_aspect(equal,adjustablebox) # 绘制圆形 return ax def plot_image_and_patch(ax,prng,size(20,20)): 绘制图像和圆形补丁。 valuesprng.random_sample(sizesize) ax.imshow(values,interpolationnone) cplt.Circle((5,5),radius5,labelpatch) ax.add_patch(c) # 移除刻度 ax.set_xticks([]) ax.set_yticks([]) def plot_histograms(ax,prng,nb_samples10000): 绘制四个直方图和一个文本注释。 params((10,10),(4,12),(50,12),(6,55)) for a,b in params: valuesprng.beta(a,b,sizenb_samples) ax.hist(values,histtypestepfilled,bins30, alpha0.8,densityTrue) # 添加小注释。 ax.annotate(Annotation,xy(0.25,4.25), xytext(0.9,0.9),textcoordsax.transAxes, vatop,haright, bboxdict(boxstyleround,alpha0.2), arrowpropsdict(arrowstyle-, connectionstyleangle,angleA-95,angleB35,rad10),) return ax def plot_figure(style_label): 设置并绘制具有给定样式的演示图。 # 在不同的图之间使用专用的RandomState实例绘制相同的“随机”值 prngnp.random.RandomState(96917002) # 创建具有特定样式的图和子图 fig,axsplt.subplots(ncols6,nrows1,numstyle_label, figsize(14.8,2.8),layoutconstrained) # 添加统一的标题标题颜色与背景颜色相匹配 background_colormcolors.rgb_to_hsv( mcolors.to_rgb(plt.rcParams[figure.facecolor]))[2] if background_color0.5: title_color[0.8,0.8,1] else: title_colornp.array([19,6,84])/256 fig.suptitle(style_label,x0.01,haleft,colortitle_color, fontsize14,fontfamilyDejaVu Sans,fontweightnormal) plot_scatter(axs[0],prng) plot_image_and_patch(axs[1],prng) plot_bar_graphs(axs[2],prng) plot_colored_lines(axs[3]) plot_histograms(axs[4],prng) plot_colored_circles(axs[5],prng) # 添加分隔线 recRectangle((10.025,-2),0.05,16, clip_onFalse,colorgray) axs[4].add_artist(rec) # 保存图片 plt.savefig(f{style_label}.png, dpi600) plt.close(fig) # 关闭当前图形以避免内存占用过多 if __name____main__: # 获取所有可用的样式列表按字母顺序排列 style_list[default,classic]sorted( style for style in plt.style.available if style !classic and not style.startswith(_)) # 绘制每种样式的演示图 for style_label in style_list: with plt.rc_context({figure.max_open_warning:len(style_list)}): with plt.style.context(style_label): plot_figure(style_labelstyle_label) plt.show()表格风格图_bmh表格风格图_classic表格风格图_dark_background表格风格图_default表格风格图_fast表格风格图_fivethirtyeight表格风格图_ggplot表格风格图_grayscale表格风格图_petroff10表格风格图_seaborn-v0_8表格风格图_seaborn-v0_8-bright表格风格图_seaborn-v0_8-colorblind表格风格图_seaborn-v0_8-dark表格风格图_seaborn-v0_8-darkgrid表格风格图_seaborn-v0_8-dark-palette表格风格图_seaborn-v0_8-deep表格风格图_seaborn-v0_8-muted表格风格图_seaborn-v0_8-notebook表格风格图_seaborn-v0_8-paper表格风格图_seaborn-v0_8-pastel表格风格图_seaborn-v0_8-poster表格风格图_seaborn-v0_8-talk表格风格图_seaborn-v0_8-ticks表格风格图_seaborn-v0_8-white表格风格图_seaborn-v0_8-whitegrid表格风格图_Solarize_Light2表格风格图_tableau-colorblind10使用Seaborn函数绘图import seaborn as sns import matplotlib.pyplot as plt # 加载数据集 irissns.load_dataset(iris,data_homeseaborn-data,cacheTrue) tipssns.load_dataset(tips,data_homeseaborn-data,cacheTrue) car_crashessns.load_dataset(car_crashes,data_homeseaborn-data,cacheTrue) penguinssns.load_dataset(penguins,data_homeseaborn-data,cacheTrue) diamondssns.load_dataset(diamonds,data_homeseaborn-data,cacheTrue) plt.figure(figsize(15,8)) # 设置画布 # 第1幅图iris数据集的散点图 plt.subplot(2,3,1) sns.scatterplot(xsepal_length,ysepal_width,huespecies, datairis) plt.title(Iris scatterplot) # 第2幅图tips 数据集的箱线图 plt.subplot(2,3,2) tipssns.load_dataset(tips,data_homeseaborn-data,cacheTrue) sns.boxplot(xday,ytotal_bill,huesmoker,datatips) plt.title(Tips boxplot) # 第3幅图tips 数据集的小提琴图 plt.subplot(2,3,3) sns.violinplot(xday,ytotal_bill,huesmoker,datatips) plt.title(Tips violinplot) # 第4幅图car_crashes 数据集的直方图 plt.subplot(2,3,4) sns.histplot(car_crashes[total],bins20) plt.title(Car Crashes histplot) # 第5幅图penguins 数据集的点图 plt.subplot(2,3,5) sns.pointplot(xisland,ybill_length_mm,huespecies,datapenguins) plt.title(Penguins pointplot) # 第6幅图diamonds 数据集的计数图 plt.subplot(2,3,6) sns.countplot(xcut,datadiamonds) plt.title(Diamonds countplot) plt.tight_layout() # 保存图片 plt.savefig(P75使用Seaborn函数绘图.png, dpi600, transparentTrue) plt.show()使用Seaborn函数绘图设置图表风格import seaborn as sns import matplotlib.pyplot as plt sns.set_style(darkgrid) # 设置图表风格为 darkgrid irissns.load_dataset(iris) # 加载 iris 数据集 # 绘制花瓣长度与宽度的散点图 sns.scatterplot(xpetal_length,ypetal_width, huespecies,datairis) plt.title(Scatter Plot of Petal Length vs Petal Width) # 保存图片 plt.savefig(P77设置图表风格.png, dpi600, transparentTrue) plt.show()设置图表风格设置颜色主题import seaborn as sns import matplotlib.pyplot as plt sns.set_palette(deep) # 设置颜色主题为deep tipssns.load_dataset(tips) # 加载 tips 数据集 # 绘制小费金额的小提琴图按照就餐日期和吸烟者区分颜色 sns.violinplot(xday,ytotal_bill,huesmoker,datatips) plt.title(Tips violinplot) # 设置图表标题 # 保存图片 plt.savefig(P78设置颜色主题.png, dpi600, transparentTrue) plt.show()设置颜色主题图表分面import seaborn as sns import matplotlib.pyplot as plt irissns.load_dataset(iris) # 加载iris数据集 # 创建 FacetGrid 对象按照种类species进行分面 gsns.FacetGrid(iris,colspecies,margin_titlesTrue) # 在每个子图中绘制花萼长度与花萼宽度的散点图 g.map(sns.scatterplot,sepal_length,sepal_width) g.set_axis_labels(Sepal Length,Sepal Width) # 设置子图标题 # 保存图片 plt.savefig(P80图表分面.png, dpi600, transparentTrue) plt.show()图表分面绘图过程from plotnine import * import seaborn as sns import warnings # 忽略 PlotnineWarning warnings.filterwarnings(ignore, categoryUserWarning, moduleplotnine) # 加载数据集 penguins sns.load_dataset(penguins, data_homeseaborn-data, cacheTrue) # 检查并处理缺失值 penguins penguins.dropna() # 创建画布和导入数据 p ggplot(penguins, aes(xbill_length_mm, ybill_depth_mm, colorspecies)) # 添加几何对象图层-散点图并进行美化 p p geom_point(size3, alpha0.7) # 设置标度 p p scale_x_continuous(nameLength (mm)) p p scale_y_continuous(nameDepth (mm)) # 设置主题和其他参数 p p theme(legend_positiontop, figure_size(6, 4)) # 保存绘图 ggsave(p, filenameP82绘图过程.png, width6, height4, dpi600)绘图过程使用绘图函数绘图import warnings from plotnine import * from plotnine.data import * # 忽略 PlotnineWarning warnings.filterwarnings(ignore, categoryUserWarning, moduleplotnine) # 散点图-mpg 数据集 p1 (ggplot(mpg) aes(xdispl, yhwy) geom_point(colorblue) labs(titleDisplacement vs Highway MPG) theme(plot_titleelement_text(size14, facebold))) # 箱线图-diamonds 数据集 p2 (ggplot(diamonds.sample(1000)) aes(xcut, yprice, fillcut) geom_boxplot() labs(titleDiamond Price by Cut) scale_fill_brewer(typequal, palettePastel1) theme(plot_titleelement_text(size14, facebold))) # 直方图-msleep 数据集 p3 (ggplot(msleep) aes(xsleep_total) geom_histogram(bins20, fillgreen, colorblack) labs(titleTotal Sleep in Mammals) theme(plot_titleelement_text(size14, facebold))) # 线图-economics 数据集 p4 (ggplot(economics) aes(xdate, yunemploy) geom_line(colorred) labs(titleUnemployment over Time) theme(plot_titleelement_text(size14, facebold))) # 条形图-presidential 数据集 presidential[duration] (presidential[end] - presidential[start]).dt.days p5 (ggplot(presidential) aes(xname, yduration, fillname) geom_bar(statidentity) labs(titlePresidential Terms Duration) scale_fill_hue(s0.90, l0.65) theme(axis_text_xelement_text(rotation90, hjust1), plot_titleelement_text(size14, facebold))) # 折线图-midwest 数据集 p6 (ggplot(midwest) aes(xarea, ypopdensity) geom_line(colorpurple) labs(titlePopulation Density vs Area) theme(plot_titleelement_text(size14, facebold))) # 保存图片 plots [p1, p2, p3, p4, p5, p6] plot_names [scatter_plot, boxplot, histogram, line_plot, bar_plot, line_chart] for plot, name in zip(plots, plot_names): plot.save(fP85使用绘图函数绘图_{name}.png, width8, height6, dpi600, transparentTrue)使用绘图函数绘图_bar_plot使用绘图函数绘图_boxplot使用绘图函数绘图_histogram使用绘图函数绘图_line_chart使用绘图函数绘图_line_plot使用绘图函数绘图_scatter_plot定义主题from plotnine import * from plotnine.data import mpg # 创建散点图 p (ggplot(mpg, aes(xdispl, yhwy, colordispl)) geom_point() # 添加点图层 scale_color_gradient(lowblue, highred) # 设置颜色渐变 labs(titleEngine Displacement vs. Highway MPG, # 设置图表标题 xEngine Displacement (L), # 设置x轴标题 yMiles per Gallon (Highway)) # 设置y轴标题 theme_minimal() # 使用最小主题 theme(axis_text_xelement_text(angle45, hjust1), # 自定义x轴文字样式 axis_text_yelement_text(colordarkgrey), # 自定义y轴文字样式 plot_backgroundelement_rect(fillwhitesmoke), # 自定义图表背景色 panel_backgroundelement_rect(fillwhite, colorblack, size0.5), # 自定义面板背景和边框 panel_grid_majorelement_line(colorlightgrey), # 自定义主要网格线颜色 panel_grid_minorelement_line(colorlightgrey, linestyle--), # 自定义次要网格线样式 legend_positionright, # 设置图例位置 figure_size(8, 6))) # 设置图形大小 # 保存图片 p.save(P88定义主题.png, dpi600, transparentTrue) # 显示图形 print(p)定义主题分面1from plotnine import * from plotnine.data import mpg # 创建散点图并按照class变量进行分面添加颜色渐变 p (ggplot(mpg, aes(xdispl, yhwy, colordispl)) geom_point() scale_color_gradient(lowblue, highorange) # 添加颜色渐变 facet_wrap(~class) # 按照汽车类型分面 labs(titleEngine Displacement vs. Highway MPG by Vehicle Class, xEngine Displacement (L), yMiles per Gallon (Highway))) # 保存图片 p.save(P89分面1.png, dpi600, transparentTrue) # 显示图片 p.draw()分面1分面2from plotnine import * from plotnine.data import mpg # 创建散点图并按照class变量进行分面根据drv变量映射颜色 p(ggplot(mpg,aes(xdispl,yhwy,colordrv)) geom_point() # 添加点图层 scale_color_brewer(typequal,paletteSet1) # 使用定性的颜色方案 facet_grid(drv ~ class) # 行是驱动类型列是汽车类型 labs(titleEngine Displacement vs. Highway MPG by Vehicle Class, xEngine Displacement (L), yMiles per Gallon (Highway)) theme_light() # 使用亮色主题 theme(figure_size(10,6), # 调整图形大小 strip_text_xelement_text(size10,colorblack,angle0), # 自定义分面标签的样式 legend_titleelement_text(colorblue,size10), # 自定义图例标题的样式 legend_textelement_text(size8), # 自定义图例文本的样式 legend_positionright)) # 调整图例位置 # 保存图片 p.save(P90分面2.png, dpi600, transparentTrue) # 显示图片 p.draw()分面2