create a bar chart using plotly

杀马特。学长 韩版系。学妹 提交于 2019-12-24 10:30:27

问题


I'm trying to create a bar chart using plotly.

The input data looks like:

In [7]: datag.ix[:,0].tolist()[1:6]
Out[7]: [2020.0, 5000.0, 6010.0, 6017.0, 6020.0]

and

In [8]:datag.ix[:,1].tolist()[1:6]
Out[8]: 
[0.005178087393490427,
 0.0014053668695097226,
 0.3174139251746979,
 0.006049724003653125,
 0.24824287385322272]

and the code is

import plotly
import plotly.offline as offline
import plotly.plotly as py 
import plotly.graph_objs as go

trace1 = go.Bar(
        x=[str(x) for x in datag.ix[:,0].tolist()[1:6]],#datag.ix[:,0].tolist()[1:6],
        y=datag.ix[:,1].tolist()[1:6],
        name='travel'
        )
data=[trace1]
layout= go.Layout(
        barmode= 'stack',
        title='Realization: 0, 0',
        xaxis=dict(title='Model'),
        yaxis=dict(title='Time (minutes)')
        )
fig= go.Figure(data=data, layout=layout)
offline.plot(fig, image='png', filename='stacked-bar')

I get the following output: However, the problem is I want to demonstrate the x-data just as strings which I tried with x=[str(x) for x in datag.ix[:,0].tolist()[1:6]]. Can some one help me to figure out how?


回答1:


Plotly 'assumes' your data type, even if you provide strings. Setting type to categorical for your xaxis resp. yaxis in layout should do the trick.

import pandas as pd
import plotly.offline as offline
import plotly.plotly as py 
import plotly.graph_objs as go

d = {'x': [None,
           2020.0, 
           5000.0, 
           6010.0, 
           6017.0, 
           6020.0], 
     'y': [None,
           0.005178087393490427,
           0.0014053668695097226,
           0.3174139251746979,
           0.006049724003653125,
           0.24824287385322272]}
datag = pd.DataFrame(data=d)

trace1 = go.Bar(
    x=[str(x) for x in datag.ix[:,0].tolist()[1:6]],
    y=datag.ix[:,1].tolist()[1:6],
    name='travel')

data = [trace1]
layout = go.Layout(
    barmode='stack',
    title='Realization: 0, 0',
    xaxis=dict(title='Model', 
               type='category'),
    yaxis=dict(title='Time (minutes)'))
fig = go.Figure(data=data, layout=layout)
offline.plot(fig, image='png', filename='stacked-bar')



来源:https://stackoverflow.com/questions/49628849/create-a-bar-chart-using-plotly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!