python plotly日期轴作为字符串而不是日期 [英] python plotly date axis as string not dates

查看:232
本文介绍了python plotly日期轴作为字符串而不是日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 python plotly 创建一个条形图,在 x 轴上将日期作为字符串/类别.出于某种原因,plotly 不断将字符串转换为日期.我的 x 轴是日期的连续时间轴",而不是我期望的类别.

I want to create a bar chart using python plotly, with on the x-axis dates as strings/categories. For some reason, plotly keeps transforming strings to dates. My x-axis is continuous "timeline" of dates, rather than categories as I would expect.

我的问题:如何构建一个条形图,其中我的日期作为类别处理,而不是日期?

My question: how can I construct a bar chart where my dates are handled as categories, rather than dates?

最小示例:

d = {'date': ['2018-08-04', '2018-08-02','2018-08-03', '2018-08-11','2018-08-11'], 'score': [3, 4, 6, 2,8]}
df = pd.DataFrame(data=d)

data = [go.Bar(
            x=df['date'],
            y=df['score']
    )]

offline.iplot(data, filename='basic-bar')

示例:

推荐答案

您可以在 layout 设置中指定轴 type.Plotly 自动检测日期,但您可以通过设置 type='category' 来覆盖它.

You can specify the axis type in your layout settings. Plotly autodetects dates but you can overwrite it by setting type='category'.

import pandas as pd
import plotly

plotly.offline.init_notebook_mode()

d = {'date': ['2018-08-04', '2018-08-02','2018-08-03', '2018-08-11','2018-08-11'], 
     'score': [3, 4, 6, 2,8]}
df = pd.DataFrame(data=d)

data = plotly.graph_objs.Bar(x=df['date'],
                             y=df['score'])

#the magic happens here
layout = plotly.graph_objs.Layout(xaxis={'type': 'category'})

fig = plotly.graph_objs.Figure([data], layout)
plotly.offline.iplot(fig)

这篇关于python plotly日期轴作为字符串而不是日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆