Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

python - Plotly: How to make a frequency plot for discrete/categorical variables?

I tried exploring everything in their website, but there is nothing regardless this (https://plotly.com/python/v3/frequency-counts/ and https://plotly.com/python/v3/discrete-frequency/ won't solve my issue). I wanted to plot a graph just like seaborn countplot (https://seaborn.pydata.org/generated/seaborn.countplot.html).

I have this dataset:

id      state       value
19292   CA          100
24592   CA          200
12492   GE          340
11022   GE          500
99091   CO          250
59820   CO          220
50281   CA          900

I just wanted a barplot with CA, GE and CO in the x-axis and 3, 2 and 2 in the y-axis, respectively.

question from:https://stackoverflow.com/questions/65887901/plotly-how-to-make-a-frequency-plot-for-discrete-categorical-variables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you set plotly as your plotting backend for pandas, you can first group your data and do:

df.groupby(["state"]).count().reset_index().plot(x='state', y='value', kind='bar')

enter image description here

Complete snippet

import pandas as pd
pd.options.plotting.backend = "plotly"
df = pd.DataFrame({'id': {0: 19292, 1: 24592, 2: 12492, 3: 11022, 4: 99091, 5: 59820, 6: 50281},
                     'state': {0: 'CA', 1: 'CA', 2: 'GE', 3: 'GE', 4: 'CO', 5: 'CO', 6: 'CA'},
                     'value': {0: 100, 1: 200, 2: 340, 3: 500, 4: 250, 5: 220, 6: 900}})

df.groupby(["state"]).count().reset_index().plot(x='state', y='value', kind='bar')

But if you would like a setup that you can expand a bit more on, I would use px.bar like so:

dfg = df.groupby(["state"]).count()
fig = px.bar(dfg, x=dfg.index, y="value")
fig.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...