PHP前端开发

使用 matplotlib python 进行多轴 x

百变鹏仔 1天前 #Python
文章标签 matplotlib
问题内容

我的目标是得到如下图所示的东西:

目前我尝试像这样构建它:

import matplotlib.pyplot as pltimport numpy as np X = ['Class 1','Class 2','Class 3','Class 4', 'Class 5', 'Class 6', 'Class 7'] sE = ['-9,51', '-13,5', '0,193', '9,564', '23,13', '-0,252', '-0,442']s = ['19,605', '28,388', '1,762', '-4,264', '-24,716', '-26,956', '0,382']eE = ['-5,364', '-7,954', '-3,756', '-0,184', '1,883', '41,876', '-0,012']X_axis = np.arange(len(X)) # plt.bar(X_axis, sE, color='red',width = 0.25, edgecolor='black') # plt.bar(X_axis+0.25, s, color='cyan',width = 0.25, edgecolor='black') # plt.bar(X_axis+0.5, eE, color='green',width = 0.25, edgecolor='black') #plt.hist([sE, s, eE], color = ['red', 'cyan', 'green'], edgecolor = 'black', histtype = 'bar')#plt.xticks(X_axis, X) plt.xlabel("Classes")  plt.title("Geographical STP A") plt.show()

但我们距离达到预期结果还有很长的路要走。我真的不知道该怎么做,你能帮我吗?


正确答案


为了能够绘图,字符串应转换为数字。

立即学习“Python免费学习笔记(深入)”;

使用基于 matplotlib 进行绘图的 pandas(或 seaborn)库,每个 x 值具有多个条形的绘图要容易得多。您的数据没有直方图数据,您似乎想要一个条形图。

这是一些代码。许多定制都是可能的。

import matplotlib.pyplot as pltimport pandas as pdx = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5', 'class 6', 'class 7']se = ['-9,51', '-13,5', '0,193', '9,564', '23,13', '-0,252', '-0,442']s = ['19,605', '28,388', '1,762', '-4,264', '-24,716', '-26,956', '0,382']ee = ['-5,364', '-7,954', '-3,756', '-0,184', '1,883', '41,876', '-0,012']# organize the data as a pandas dataframedf = pd.dataframe({'class': x, 'se': se, 's': s, 'ee': ee})# convert strings to numericdf['se'] = df['se'].str.replace(',','.').astype(float)df['s'] = df['s'].str.replace(',','.').astype(float)df['ee'] = df['ee'].str.replace(',','.').astype(float)ax = df.set_index('class').plot(kind='bar')ax.set_title("geographical stp a")ax.tick_params(axis='x', rotation=0)plt.show()

可能的定制可能包括:

ax = df.set_index('Class').plot(kind='bar', color=['crimson', 'limegreen', 'dodgerblue'])ax.set_title("Geographical STP A")ax.tick_params(axis='x', rotation=0, length=0)  # rotate tick labels horizontally, remove tick markax.grid(True, axis='y')  # add a grid in the y directionax.set_xlabel('')  # remove superfluous x labelfor dir in ['top', 'bottom', 'right']:    ax.spines[dir].set_visible(False)  # remove the border around the plot

ps:数据框如下所示:

类sesee标题>1 类-9.5119.605-5.3642 类-13.528.388-7.9543 级0.1931.762-3.7564 类9.564-4.264-0.1845 级23.13-24.7161.8836 级-0.252-26.95641.8767 类-0.4420.382-0.012表>