简体   繁体   English

更改 plot 的 x 轴

[英]change x-axis of a plot

I am trying to create a visualization of vehicles passing by in the first 25 weeks of the years 2015-2020 all in one graph (one curve for every year).我正在尝试将 2015-2020 年的前 25 周内经过的车辆可视化,所有这些都在一张图中(每年一条曲线)。

df_data_groups = df_data[(df_data['week']<=25)].groupby(['year','week'])
df_data_weekly = df_data_groups[['NO','nr_of_vehicles']].mean()

fig, ax = plt.subplots()
bp = df_data_weekly['nr_of_vehicles'].groupby('year').plot(ax=ax)

The following is what i get以下是我得到的

阴谋

The x-axis is not right. x 轴不对。 It should not contain the year, only the weeks, but I don't know how to solve this correctly.它不应该包含年份,只有几周,但我不知道如何正确解决这个问题。 It also is not allowing me to create a legend to show which lines belongs to the color of the line, by using:它也不允许我创建一个图例来显示哪些线条属于线条的颜色,使用:

bp.set_legend()

The index shown, is the index of the last dataframe in the group.显示的索引是组中最后一个 dataframe 的索引。 This dataframe has a 2-level index: the year and the week.这个 dataframe 有 2 级索引:年和周。 Dropping the first index (the year) will only show the week:删除第一个索引(年份)将只显示周:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df_data = pd.DataFrame({'year': np.repeat(np.arange(2015, 2021), 52),
                        'week': np.tile(np.arange(1, 53), 6),
                        'nr_of_vehicles': 200_000 + np.random.randint(-9_000, 10_000, 52 * 6).cumsum()})
df_data_groups = df_data[(df_data['week'] <= 25)].groupby(['year', 'week'])
df_data_weekly = df_data_groups[['nr_of_vehicles']].mean()

fig, ax = plt.subplots()
for year, df in df_data_weekly['nr_of_vehicles'].groupby('year'):
    df.reset_index(level=0, drop=True).plot(ax=ax, label=year)
ax.legend()
ax.margins(x=0.02)
plt.show()

示例图

PS: Note that in the question's code, bp is a list of axes, one ax per year. PS:请注意,在问题的代码中, bp是一个轴列表,每年一个ax In this case, all of them point to the same ax .在这种情况下,它们都指向同一个ax bp is organized as a pandas Series, to obtain the legend, get one of the axes: bp[2015].legend() (or bp.iloc[0].legend() ). bp组织为 pandas 系列,要获得图例,请获取轴之一: bp[2015].legend() (或bp.iloc[0].legend() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM