简体   繁体   English

x标签的月份折线图,但使用每周数据

[英]line chart with months for x-labels but using weekly data

Below is script for a simplified version of the df in question:以下是相关 df 的简化版本的脚本:

import pandas as pd
    
df = pd.DataFrame({ 
                   'week': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],
                   'month' : ['JAN','JAN ','JAN','JAN','FEB','FEB','FEB','FEB','MAR','MAR',
                              'MAR','MAR','APR','APR','APR','APR','APR'],
                   'weekly_stock' : [4,2,5,6,2,3,6,8,7,9,5,3,5,4,5,8,9]
                 })
df

    week    month   weekly_stock
0   1       JAN           4
1   2       JAN           2
2   3       JAN           5
3   4       JAN           6
4   5       FEB           2
5   6       FEB           3
6   7       FEB           6
7   8       FEB           8
8   9       MAR           7
9   10      MAR           9
10  11      MAR           5
11  12      MAR           3
12  13      APR           5
13  14      APR           4
14  15      APR           5
15  16      APR           8
16  17      APR           9

As it currently stands, the script below produces a bar chart with week for x-labels按照目前的情况,下面的脚本会为 x-labels 生成一个带有week的条形图

# plot chart
labels=df.week

line=df['weekly_stock']

fig, ax = plt.subplots(figsize=(20,8))

line1=plt.plot(line, label = '2019')

ax.set_xticks(x)
ax.set_xticklabels(labels, rotation=0)

ax.set_ylabel('Stock')
ax.set_xlabel('week')
plt.title('weekly stock')

在此处输入图像描述

However, I would like to have the month as the x-label.但是,我希望将month作为 x-label。

INTENDED PLOT:预期 PLOT:

在此处输入图像描述

Any help would be greatly appreciated.任何帮助将不胜感激。

My recommendation is to have a valid datetime values column instead of 'month' and 'week' , like you have.我的建议是有一个有效的日期时间值列而不是'month''week' ,就像你一样。 Matplotlib is pretty smart when working with valid datetime values, so I'd structure the dates like so first: Matplotlib 在使用有效的日期时间值时非常聪明,所以我首先像这样构造日期:

import pandas as pd
import matplotlib.pyplot as plt

# valid datetime values in a range
dates = pd.date_range(
    start='2019-01-01', 
    end='2019-04-30',
    freq='W',         # weekly increments
    name='dates', 
    closed='left'
    )             

weekly_stocks = [4,2,5,6,2,3,6,8,7,9,5,3,5,4,5,8,9]

df = pd.DataFrame(
    {'weekly_stocks': weekly_stocks},
    index=dates # set dates column as index                   
    )

df.plot(
    figsize=(20,8),
    kind='line', 
    title='Weekly Stocks',
    legend=False,
    xlabel='Week',
    ylabel='Stock'
    )

plt.grid(which='both', linestyle='--', linewidth=0.5)

在此处输入图像描述

Now this is a fairly simple solution.现在这是一个相当简单的解决方案。 Take notice that the ticks appear exactly where the weeks are;请注意,刻度恰好出现在星期的位置; Matplotlib did all the work for us! Matplotlib 为我们做了所有的工作!

  1. (easier) You can either lay the "data foundation" prior to plotting correctly, ie, format the data for Matplotlib to do all the work like we did above(think of the ticks being the actual date-points created in the pd.date_range() ). (更容易)您可以在正确绘制之前奠定“数据基础”,即格式化 Matplotlib 的数据以完成我们上面所做的所有工作(认为刻度是在pd.date_range()中创建的实际日期点pd.date_range() )。

  2. (harder) Use tick locators/formatters as mentioned in docs here (更难)使用此处文档中提到的刻度定位器/格式化程序

Hope this was helpful.希望这会有所帮助。

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

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