Matplotlib:如何在X轴上绘制带有分类数据的线? [英] Matplotlib: how to plot a line with categorical data on the x-axis?

查看:90
本文介绍了Matplotlib:如何在X轴上绘制带有分类数据的线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制几行(而不是条形图,如这种情况)。我的y值是 float ,而x值是分类数据。如何在 matplotlib 中做到这一点?

I am trying to plot a few lines (not a bar plot, as in this case). My y values are float, whereas x values are categorical data. How to do this in 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']

我正在使用的代码无法提供我想要的内容:

The code I am using, which does not give me what I want:

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()


解决方案

关于某些语法,您的代码看起来不正确:

Your code looks incorrect with regards to some syntax:

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

当我修复这些绘图后,您的行

When I fixed these the plotting worked fine, your line

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

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

is a correct way to assign a list to the x axis.

这篇关于Matplotlib:如何在X轴上绘制带有分类数据的线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆