首页 > 解决方案 > 无法在 pyplot 图表中按月对 x 轴进行分组(Python)

问题描述

我正在使用 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 私人信息的副本。

非常感谢您。

标签: pythondataframematplotlibdata-visualization

解决方案


您的问题基本上有两个部分:

  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())

结果:

在此处输入图像描述


推荐阅读