使用与原始数组相同的顺序绘制具有字符串数组的x轴,并且不在matplotlib中按字母顺序对其进行排序 [英] Plot x-axis with string array as in the same order in original array and not sort it alphabetically in matplotlib
问题描述
Numpy或Matplotlib都在更改我的np.array的顺序,并且与我的情节冲突.这会导致月份混乱,而相应的数据仍处于相同的顺序,这会使绘图看起来很奇怪:
Either Numpy or Matplotlib is changing the order of my np.array and it's conflicting with my plot. It's causing the months to be out of order while the corresponding data to still be in the same order which is causing the plot to look weird:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
f = np.array([53, 56, 63, 72, 79, 86, 89, 88, 83, 74, 65, 56])
month = np.array(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])
plt.plot(month, f)
plt.xlabel('Month')
plt.ylabel('Temperature')
plt.title('Average Monthly Temperature in Elizabeth City, NC')
plt.show()
这是我在JupyterNotebook中得到的输出:
This is what i get as output in JupyterNotebook:
推荐答案
由于month
是字符串数组,因此plt.plot()
命令按字母顺序对其进行排序.因此,我们必须使用xticks
,然后按如下所示进行绘制,以与原始数组month
相同的顺序获取字符串.
Since month
is a string array, plt.plot()
command is sorting it alphabetically. So, we have to use the xticks
and then plot it like below to get the strings in the same order as it were in the original array month
.
In [16]: f = np.array([53, 56, 63, 72, 79, 86, 89, 88, 83, 74, 65, 56])
...: month = np.array(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])
...: plt.xticks(range(len(f)), month)
...: plt.plot(f)
情节:
注意:有关更多自定义图的信息,请参见: pylab日期演示
Note: For more customized plots refer: pylab date demo
这篇关于使用与原始数组相同的顺序绘制具有字符串数组的x轴,并且不在matplotlib中按字母顺序对其进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!