ay-*_*ron 2 python csv matplotlib python-3.x
这是在一台Windows 7 x64位机器上,在PyCharm教育版1.0.1编译器中运行python 3.4.3 x64位.用于此计划的数据来自纽约市的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()
Run Code Online (Sandbox Code Playgroud)
它创建了几乎正确格式化的图形.唯一的问题是它对Bike 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()
Run Code Online (Sandbox Code Playgroud)
第二组代码使用与第一组代码相同的数据集,并且已从原始代码更改为适合citi自行车数据.我的谷歌已经筋疲力尽了.我已经尝试重新格式化xticks,将第二个代码的片段添加到第一个代码中,将第一个代码的片段添加到第二个代码中等等.这可能是我面对面的东西,但我看不到它.任何帮助表示赞赏.
您想使用绘图功能仅绘制使用次数,然后将x标签设置为自行车ID编号.所以当你绘图时,不要包括自行车ID号.做plt.plot(c).如果给plot函数只有一个参数,它会自己创建x值,在本例中为range(len(c)).然后,您可以将x轴上的标签更改为自行车ID.这是通过plt.xticks完成的.您需要将它创建的x值列表和标签列表传递给它.那就是plt.xticks(范围(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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15484 次 |
| 最近记录: |