这一切都是在Windows7x64位的机器上进行的,在PyCharmEducationalEdition1.0.1编译器中运行Python3.4.3x64位。此程序使用的数据取自纽约市的花旗自行车计划(数据见:http://www.citibikenyc.com/system-data)。
我已经对数据进行了排序,这样我就有了一个新的CSV文件,其中只有uniqe bike ID和每辆自行车被骑了多少次(文件名为sorted_bike_Uses.CSV)。我试着用自行车ID做一个图表来反对使用次数(X轴上的自行车ID,Y轴上使用的x)。我的代码如下:

import pandas as pd
import matplotlib.pyplot as plt

# read in the file and separate it into two lists
a = pd.read_csv('Sorted_Bike_Uses.csv', header=0)
b = a['Bike ID']
c = a['Number of Uses']

# create the graph
plt.plot(b, c)

# label the x and y axes
plt.xlabel('Bicycles', weight='bold', size='large')
plt.ylabel('Number of Rides', weight='bold', size='large')

# format the x and y ticks
plt.xticks(rotation=50, horizontalalignment='right', weight='bold', size='large')
plt.yticks(weight='bold', size='large')

# give it a title
plt.title("Top Ten Bicycles (by # of uses)", weight='bold')

# displays the graph
plt.show()

它创建一个格式几乎正确的图形。唯一的问题是,它对自行车识别码进行分类,使其按数字顺序排列,而不是按使用顺序排列。。看起来是这样的:
my_plot = a.sort(columns='Number of Uses', ascending=True).plot(kind='bar', legend=None)

# labels the x and y axes
my_plot.set_xlabel('Bicycles')
my_plot.set_ylabel('Number of Rides')

# sets the labels along the x-axis as the names of each liquor
my_plot.set_xticklabels(b, rotation=45, horizontalalignment='right')

# displays the graph
plt.show()

第二组代码使用与第一组代码相同的数据集,并已从原始代码更改为适合花旗自行车数据。。。如有任何帮助,我们将不胜感激。

最佳答案

。。只需做plt.plt.plot(c)如果只给plot函数一个参数,它将创建x值本身,在本例中为range(len(c))。然后你可以改变X轴上的标签到自行车ID。。您需要将它创建的x值列表和标签列表传递给它。那就是plt.xticks(range(len(c)),b)。
试试这个:

import pandas as pd
import matplotlib.pyplot as plt

# read in the file and separate it into two lists
a = pd.read_csv('Sorted_Bike_Uses.csv', header=0)
b = a['Bike ID']
c = a['Number of Uses']

# create the graph
plt.plot(c)

# label the x and y axes
plt.xlabel('Bicycles', weight='bold', size='large')
plt.ylabel('Number of Rides', weight='bold', size='large')

# format the x and y ticks
plt.xticks(range(len(c)), b, rotation=50, horizontalalignment='right', weight='bold', size='large')
plt.yticks(weight='bold', size='large')

# give it a title
plt.title("Top Ten Bicycles (by # of uses)", weight='bold')

# displays the graph
plt.show()

关于python - pyplot x轴正在排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31117984/

10-13 07:37