python - pyplot x轴被排序

标签 python csv python-3.x matplotlib

这一切都在 Windows 7 x64 位机器上,运行 python 3.4.3 x64 位,在 PyCharm 教育版 1.0.1 编译器中。用于此计划的数据取自纽约市的 Citi Bike 计划(数据可在此处找到:http://www.citibikenyc.com/system-data)。

我对数据进行了排序,这样我就有了一个新的 CSV 文件,其中仅包含唯一的自行车 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,将第二个代码片段添加到第一个代码中,将第一个代码片段添加到第二个代码片段中,等等。它可能正对着我,但我看不到它。感谢您的帮助。

最佳答案

您只想使用绘图函数绘制使用次数,然后将 x 标签设置为自行车 ID 号。所以当你绘图时,不要包括自行车 ID 号。只需执行 plt.plot(c)。如果您只给 plot 函数一个参数,它会自己创建 x 值,在本例中为 range(len(c))。然后您可以将 x 轴上的标签更改为自行车 ID。这是通过 plt.xticks 完成的。您需要将它创建的 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/

相关文章:

python - 删除python中变量的特定部分

python - 将 XML 字符作为字符串读入 ElementTree

python - 循环命名元组

python - connection.cursor() 作为游标会创建新连接吗?

python - 尝试在 python 文件之间导入时出错

Python/Django - 从对象变量值中获取带有索引的列表值

python - python 中的 ffill 作为链式方法和作为参数有什么区别?

python - 变量分配的最佳实践以及为什么?

python - 在 Pandas read_csv 期间标记化数据时出错。如何真正看到坏线?

python-3.x - 在 Pandas DataFrame 中拆分列列表