简体   繁体   中英

Plotly graph : show number of occurrences in bar-chart

I try to plot a bar-chart from a givin dataframe.

  • x-axis = dates
  • y-axis = number of occurences for each month

The result should be a barchart. Each x is an occurrence.

x xx x
2020-1 2020-2 2020-3 2020-4 2020-5

I tried but don't get the desired result as above.

import datetime as dt
import pandas as pd
import numpy as np
import plotly.offline as pyo
import plotly.graph_objs as go
  
# initialize list of lists
data = [['a', '2022-01-05'], ['a', '2022-02-14'], ['a', '2022-02-15'],['a', '2022-05-14']]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Date'])
  
# print dataframe.
df['Date']=pd.to_datetime(df['Date'])
# plot dataframe 
trace1=go.Bar(
#    
    x = df.Date.dt.month,
    y = df.Name.groupby(df.Date.dt.month).count()
)
data=[trace1]

fig=go.Figure(data=data)
pyo.plot(fig)

Remove the last line and write instead: fig.show()

Edit: It's unclear to me whether you have 1 dimensional or 2 dimensional data here. Supposing you have 1d data, this is, just a bunch of dates that you want to aggregate in a bar chart, simply do this:

# initialize list of lists
data = ['2022-01-05', '2022-02-14',  '2022-02-15', '2022-05-14']
# Create the pandas DataFrame
df = pd.DataFrame(data)
# plot dataframe 
fig = px.bar(df)

If, instead, you have 2d data then what you want is a scatter plot, not a bar chart.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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