【问题标题】:Matplotlib: how to plot a line with categorical data on the x-axis?Matplotlib:如何在 x 轴上绘制一条带有分类数据的线?
【发布时间】:2015-11-27 13:04:45
【问题描述】:

我正在尝试绘制几行(不是条形图,如this case)。我的 y 值为 float,而 x 值为 categorical data。如何在matplotlib 中做到这一点?

我的价值观:

data1=[5.65,7.61,8.17,7.60,9.54]
data2=[7.61,16.17,16.18,19.54,19.81] 
data3=[29.55,30.24,31.51,36.40,35.47]

我的类别:

x_axis=['A','B','C','D','E']

我正在使用的代码没有给我想要的:

import matplotlib.pyplot as plt
fig=plt.figure() #Creates a new figure
ax1=fig.add_subplot(111) #Plot with: 1 row, 1 column, first subplot.
line1 = ax1.plot(str(x_axis), data1,'ko-',label='line1') #Plotting data1
line2 = ax1.plot(str(x_axis), data2,'ro-',label='line2') #Plotting data2
line3 = ax1.plot(str(x_axis), data3,'mo-',label='line3') #Plotting data3
plt.xticks(range(len(data3)), x_axis, size='small')
ax1.set_ylim(0,51)
ax1.set_ylabel('y values',fontsize=12)
#Assigning labels
lines = line1+line2+line3
labels = [l.get_label() for l in lines]
ax1.legend(lines,labels,loc='upper center', prop={'size':10}, bbox_to_anchor=(0.5, -0.13), fancybox=True, shadow=True, ncol=5)
ax1.set_xlabel('Categories',fontsize=14)
plt.setp(ax2.get_xticklabels(), visible=True)
title_string=('Plotting categories vs y values in matplotlib')
plt.suptitle(title_string, y=1.0, fontsize=17)
fig.tight_layout()
fig.subplots_adjust(top=0.92,bottom=0.2)
plt.show() 
plt.savefig('myplot.jpg',bbox_inches='tight')
plt.close()

【问题讨论】:

  • 那是指条形图。这是一个线图。
  • 您希望 x_axis 为“A”、“B”...而不是 1,2...,对吗?您可以使用xticks 执行此操作。如果你想要更复杂的东西,结果的图像会很有用。

标签: python matplotlib plot categorical-data


【解决方案1】:

Matplotlib版本2.1.0允许plotting categorical variables directly,像往常一样调用plt.plot(x,y),不需要使用rangeget_xticklabels()

line1 = plt.plot(x_axis, data1,'ko-',label='line1')
line2 = plt.plot(x_axis, data2,'ro-',label='line2') 
line3 = plt.plot(x_axis, data3,'mo-',label='line3')

【讨论】:

    【解决方案2】:

    您的代码在某些语法方面看起来不正确:

    line1 = ax1.plot(data1,'ko-',label='line1') #no need for str(x_axis)
    line2 = ax1.plot(data2,'ro-',label='line2') 
    line3 = ax1.plot(data3,'mo-',label='line3') 
    

    plt.setp(ax1.get_xticklabels(), visible=True) #not ax2
    

    当我修复这些时,绘图工作正常,你的线

    plt.xticks(range(len(data3)), x_axis, size='small')
    

    是将列表分配给 x 轴的正确方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 2016-09-26
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多