【问题标题】:Plotly xaxis in weekday name在工作日名称中绘制 xaxis
【发布时间】:2018-08-17 06:57:26
【问题描述】:

我查看了文档,但他们似乎没有提及。

https://plot.ly/python/axes/

如何更改 x 轴上的标签以显示“Mon 20-7”、“Tue 21-7”等。 xaxis 使用的“日期”格式为“20-7-2018 11:00:00am”等。

我使用以下 Python Plotly 脚本:

trace0=go.Scatter(x=df_pre.index,y=df_pre['Total'],line=dict(color=('rgb(16,25,109)'),width=1),name='Period_1')

trace1=go.Scatter(x=df_post.index,y=df_post['Total'],line=dict(color=('rgb(77,221,26)'),width=2),name='Period_2')

data=[trace0,trace1]

layout=dict(title='Total',width=960,height=768,
              yaxis=dict(title='Avg',ticklen=5,zeroline=False,gridwidth=2,),
              xaxis=dict(title='Date',ticklen=5,zeroline=False,gridwidth= 2,))

fig=dict(data=data,layout=layout)

iplot(fig,filename='Total')

任何帮助将不胜感激

【问题讨论】:

    标签: python plotly


    【解决方案1】:

    如果您想在 xaxis 上看到“Tue 14-08”,请按照以下步骤操作(在下面的代码中添加):

    1.根据您的要求创建一个列

    df_pre["date2"] = df_pre["date"].apply(lambda x: datetime.datetime.\
                    strptime(x,"%d-%m-%Y %I:%M:%S%p").strftime("%a %d-%m"))
    print(df_pre["date2"])
    0    Tue 14-08
    1    Wed 15-08
    2    Thu 16-08
    3    Fri 17-08
    4    Sat 18-08
    Name: date2, dtype: object
    

    2.从您希望在 xaxis 上看到的列创建一个名为“list_”的列表 (df_pre["date2"])

    list_ = df_pre["date2"].tolist()
    print(list_)
    ['Tue 14-08', 'Wed 15-08', 'Thu 16-08', 'Fri 17-08', 'Sat 18-08']
    

    3.在 xaxis Layout 中放入两个参数 tickvalsticktext:在第一个参数中输入要迭代多少个值。在第二个参数中选择你的文本(例如我们从列df["date2"] 得到的list_

    layout=dict(title="Total",width=960,height=768,
                yaxis=dict(title="Avg",ticklen=5,zeroline=False,gridwidth=2),
                xaxis=dict(title="Date",ticklen=5,zeroline=False,gridwidth=2,
                           #Choose what you want to see on xaxis! In this case list_
                           tickvals=[i for i in range(len(list_))],
                           ticktext=list_
                           ))
    

    输出应该是这样的:

    我在文档中找不到您需要的选项。但别忘了,你可以准备好数据,之后可以放入x,使用Pythonpandas

    #Import all what we need
    import pandas as pd
    import plotly
    import plotly.graph_objs as go
    #Create first DataFrame
    df_pre = pd.DataFrame({"date":["14-08-2018 11:00:00am",
                                   "15-08-2018 12:00:00am",
                                   "16-08-2018 01:00:00pm",
                                   "17-08-2018 02:00:00pm",
                                   "18-08-2018 03:00:00pm"],
                           "number":["3","5","10","18","22"]})
    #Create a column which corresponds to your requirements
    df_pre["dow"] = pd.to_datetime(df_pre["date"], \
                                   format="%d-%m-%Y %I:%M:%S%p").dt.weekday_name
    df_pre["firstchunk"] = df_pre["dow"].astype(str).str[0:3]
    df_pre["lastchunk"] = df_pre["date"].astype(str).str[0:5]
    df_pre["final"] = df_pre["firstchunk"] + " " + df_pre["lastchunk"]
    #Check DataFrame
    print(df_pre)
    #Repeat all the actions above to the second DataFrame
    df_post = pd.DataFrame({"date":["14-08-2018 11:00:00am",
                                    "15-08-2018 12:00:00am",
                                    "16-08-2018 01:00:00pm",
                                    "17-08-2018 02:00:00pm",
                                    "18-08-2018 03:00:00pm"],
                            "number":["6","8","12","19","23"]})
    df_post["dow"] = pd.to_datetime(df_post["date"], \
                                    format="%d-%m-%Y %I:%M:%S%p").dt.weekday_name
    df_post["firstchunk"] = df_post["dow"].astype(str).str[0:3]
    df_post["lastchunk"] = df_post["date"].astype(str).str[0:5]
    df_post["final"] = df_post["firstchunk"] + " " + df_post["lastchunk"]
    print(df_post)
    #Create list needed for xaxis
    list_ = df_pre["final"].tolist()
    print(list_)
    #Prepare data
    trace0=go.Scatter(x=df_pre["date"],y=df_pre["number"],
                      line=dict(color=("rgb(16,25,109)"),width=1),name="Period_1")
    trace1=go.Scatter(x=df_post["date"],y=df_post["number"],
                      line=dict(color=("rgb(77,221,26)"),width=2),name="Period_2")
    data = [trace0,trace1]
    #Prepare layout
    layout=dict(title="Total",width=960,height=768,
                yaxis=dict(title="Avg",ticklen=5,zeroline=False,gridwidth=2),
                xaxis=dict(title="Date",ticklen=5,zeroline=False,gridwidth=2,
                           #Choose what you want to see on xaxis! In this case list_
                           tickvals=[i for i in range(len(list_))],
                           ticktext=list_
                           ))
    fig = go.Figure(data=data, layout=layout)
    #Save plot as "Total.html" in directory where your script is
    plotly.offline.plot(fig, filename="Total.html", auto_open = False)
    

    更新:您也可以尝试使用datetime 来实现您想要的(更简单):

    #Import all what we need
    import pandas as pd
    import plotly
    import plotly.graph_objs as go
    import datetime
    #Create first DataFrame
    df_pre = pd.DataFrame({"date":["14-08-2018 11:00:00am",
                                   "15-08-2018 12:00:00am",
                                   "16-08-2018 01:00:00pm",
                                   "17-08-2018 02:00:00pm",
                                   "18-08-2018 03:00:00pm"],
                           "number":["3","5","10","18","22"]})
    #Create a column which corresponds to your requirements
    df_pre["date2"] = df_pre["date"].apply(lambda x: datetime.datetime.\
                strptime(x,"%d-%m-%Y %I:%M:%S%p").strftime("%a %d-%m"))
    #Check DataFrame
    print(df_pre)
    #Repeat all the actions above to the second DataFrame
    df_post = pd.DataFrame({"date":["14-08-2018 11:00:00am",
                                    "15-08-2018 12:00:00am",
                                    "16-08-2018 01:00:00pm",
                                    "17-08-2018 02:00:00pm",
                                    "18-08-2018 03:00:00pm"],
                            "number":["6","8","12","19","23"]})
    df_post["date2"] = df_post["date"].apply(lambda x: datetime.datetime.\
                 strptime(x,'%d-%m-%Y %I:%M:%S%p').strftime("%a %d-%m"))
    print(df_post)
    #Create list that needed to xaxis
    list_ = df_pre["date2"].tolist()
    print(list_)
    #Prepare data
    trace0=go.Scatter(x=df_pre["date"],y=df_pre["number"],
                      line=dict(color=("rgb(16,25,109)"),width=1),name="Period_1")
    trace1=go.Scatter(x=df_post["date"],y=df_post["number"],
                      line=dict(color=("rgb(77,221,26)"),width=2),name="Period_2")
    data = [trace0,trace1]
    #Prepare layout
    layout=dict(title="Total",width=960,height=768,
                yaxis=dict(title="Avg",ticklen=5,zeroline=False,gridwidth=2),
                xaxis=dict(title="Date",ticklen=5,zeroline=False,gridwidth=2,
                           #Choose what you want to see on xaxis! In this case list_
                           tickvals=[i for i in range(len(list_))],
                           ticktext=list_
                           ))
    fig = go.Figure(data=data, layout=layout)
    #Save plot as "Total.html" in directory where your script is
    plotly.offline.plot(fig, filename="Total.html")
    

    【讨论】:

    • 嗨 Oysiyl,现在日期列是字符串。当我将它转换为日期时间对象时,工作日名称就消失了。我需要转换为 datetime 对象,以便我可以进行时移。如何保留格式“Tue 14-08”但 dtype 是时间对象?
    • @Marlin,我今天尝试解决您的问题,但没有成功。对不起=(也许其他人可以帮助你。我现在看到一种可能的解决方案:使用日期时间进行时间转换,看起来像(2018-08-14)。然后,在计算后再次将此日期列格式化为字符串看起来像(星期二08-14)。
    • @Oysisyl,我明白了。你上面的建议有效!!!我现在唯一的问题是图中的 x 轴显示“Fri 20-07 03:00:00”。我们有没有机会摆脱情节显示中的时间部分?我无法删除数据中的时间,因为这会删除数据点的数量。
    • @Marlin,您可以创建列表,例如df["date"].tolist()。然后使用.str.split(" ")[0:2] 拆分它(并选择前三个块)。你应该得到你想要的作为列表中的元素。并将此列表作为x 发送到trace。哦,那是改变数据点的数量。你的情节如何?您对每个 day 都有几点看法,或者为什么时间部分对您来说很重要?查看ticktexttickvals here。也许您可以使用那些ticks 自定义 xaxis
    • @Oysisyl,非常感谢.. 是的,您的回复解决了我的问题。非常感谢。
    【解决方案2】:

    你可以这样做:-

    data = [go.Scatter(x=df.Date, y=df.High)]
    

    如需更多参考,您可以参考此链接:- https://plot.ly/python/time-series/

    学习愉快!

    【讨论】:

    • 他在代码中做到了这一点并且无法解决,这就是为什么他要求一种新的方法来做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2022-01-08
    • 1970-01-01
    • 2020-06-28
    相关资源
    最近更新 更多