【问题标题】:Not able to group x-axis by month in a pyplot chart (Python)无法在 pyplot 图表中按月对 x 轴进行分组(Python)
【发布时间】:2021-03-24 00:25:34
【问题描述】:

我正在使用 python 开始我的第一个“项目”,我需要一些帮助。

我正在使用 pyplot 创建一个图表,显示自创建帐户以来我在 Linkedin 的连接数如何增长。

我在尝试按月和年对 X 轴进行分组时遇到问题。我发现将它们分组的方式并不好,因为它跳过了我没有任何新联系的那几个月。

我想知道是否有人知道我该如何解决这个问题。

import pandas as pd
import datetime
import matplotlib.pyplot as plt
from matplotlib import rcParams
df = pd.read_csv("/Users/ignaciolorenzoqueralt/Desktop/linkedin.pythonproject/connections_clean.csv")

df.head(2)

def fun(date):
    return datetime.datetime.strptime(date,"%d %b %Y").strftime("%Y-%m")


df["Connected On"] = df["Connected On"].apply(fun)


df = df.sort_values(by="Connected On")
df.reset_index(inplace=True)
df.reset_index(inplace=True)

df.drop(columns="index",inplace=True)
df.rename(columns={"level_0":"number"},inplace=True)

print(df)

x = df["Connected On"]
y = df["number"]


rcParams["figure.figsize"] = 15,8
plt.plot(x, y, label="Ignacio's nº of Connections")

plt.xlabel("Date")
plt.ylabel("Number of connections")
plt.xticks(rotation=45)

plt.legend()
#plt.grid()

plt.show()

Here is what I have coded:

附加到此链接 (https://docs.google.com/spreadsheets/d/1yIGQGoCcmq0JOD2Im0B8CQ0oT2fqFh5cKxKO5i8_uAU/edit?usp=sharing),您会发现没有此项目所基于的 csv 私人信息的副本。

非常感谢您。

【问题讨论】:

    标签: python dataframe matplotlib data-visualization


    【解决方案1】:

    你的问题基本上有两部分:

    1. 对数据进行分组(否则当每月有多个条目时,绘图会导致奇怪的结果)
    2. 绘制数据并说明“缺失值”,即没有条目的月份

    第一部分可以解决

    #get unique months --> no duplicate x values
    x = df["Connected On"].unique()
    
    #group by months, then take max number for each month
    y = df.groupby("Connected On").max()["number"]
    

    第二部分与 matplotlib 处理日期的方式有关。我认为在您的情况下,日期被解释为strings,因此每个 x,y 对的绘制在 x 轴上没有任何线性。为了实现时间线性和连续性,您需要为 matplotlib 提供完整的日期时间对象,这可以通过

    x = pd.to_datetime(df["Connected On"].unique())
    

    结果:

    【讨论】:

    • 非常感谢@BenB!我真的很感谢你的帮助。你帮了我很多。如果可能的话,我想问你另一个问题:当我应用你提到的更改时,y 轴恰好按年分组,而不是按年-月分组。我该如何改变呢?
    • 很高兴我能帮上忙。对不起,我不太明白你的第二个问题。你的意思是y = df.groupby("Connected On").max()["number"] 不是在几个月内工作,而是在几年内工作?我不得不重新创建你的 csv 文件的一小部分,因为我不被允许下载它。与您的相比,我的 csv 文件可能发生了一些变化。
    • 没错。我没有诸如 2016-03、2016-05 之类的标签。我只有2016、2017等等。为了在你的图中显示它,我应该修改 .csv 文件还是只是改变我对数据进行分组的方式?再次感谢
    • 您的数据框是否包含year-monthyear 格式的日期?否则,您的 fun 方法可能不适用于 csv 中给出的日期。
    猜你喜欢
    • 1970-01-01
    • 2018-08-19
    • 2019-02-01
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2017-01-25
    • 1970-01-01
    相关资源
    最近更新 更多