【发布时间】:2015-09-16 01:15:26
【问题描述】:
这一切都在 Windows 7 x64 位机器上,运行 python 3.4.3 x64 位,在 PyCharm 教育版 1.0.1 编译器中。该计划使用的数据取自纽约市的 Citi Bike 计划(数据可在此处找到:http://www.citibikenyc.com/system-data)。
我已经对数据进行了排序,这样我就有了一个新的 CSV 文件,其中只有 uniqe 自行车 ID 和每辆自行车的骑行次数(文件名为 Sorted_Bike_Uses.csv)。我正在尝试使用自行车 ID 与使用次数(x 轴上的自行车 ID,y 轴上的使用次数)制作一个图表。我的代码如下所示:
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()
它创建了一个格式几乎正确的图表。唯一的问题是它对自行车 ID 进行排序,以便它们按数字顺序排列,而不是按使用顺序排列。我曾尝试重新利用用于制作类似图表的旧代码,但它只会制作更糟糕的图表,不知何故绘制了两组数据。它看起来像这样:
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()
第二组代码使用与第一组代码相同的数据集,并且已从原始代码中更改以适合花旗自行车数据。我的 google-fu 已经筋疲力尽了。我尝试重新格式化 xticks,将第二个代码的片段添加到第一个代码中,将第一个代码的片段添加到第二个代码中,等等。这可能是我正面临的事情,但我看不到它。任何帮助表示赞赏。
【问题讨论】:
-
因为
plot(b, c)将b与c对比。如果您想按游乐设施的顺序绘制它们,请使用作为其排序数字的 xaxis。 -
我想绘制它们,以便自行车 ID 在 x 轴上,并按照它们在 csv 文件中的顺序保留。在文件中,它们按照骑车次数最少到骑车次数最多的顺序排列。然而,当它们被绘制在图表上时,它们是按数字顺序排序的,而不是按最少骑乘次数排序。在代码中的某处,订单系统正在切换。
标签: python csv python-3.x matplotlib