Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

pandas - How to plot two different features while counting them?

Suppose I have a DataFrame like this:

*Age* *RemoteWork*
18  Sometimes
24  Never
30  Sometimes
15  Never
24  Sometimes

and it goes on like that.

How would I plot a graph for example "which shows HOW MANY 24 year olds are in Never group"?

Suppose there are more ages and remote work values. I am basically trying to create a histogram of age which shows remote work value and count.

I am sorry if this is not very clear. If you need anymore info please tell me.

question from:https://stackoverflow.com/questions/65649505/how-to-plot-two-different-features-while-counting-them

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

1 Answer

0 votes
by (71.8m points)

Clearly your sample data set is limited and does not have additional attributes. You really need to consider how you want to visualise, then it's straight forward. Using matplotlib two examples.

  1. a scatter where have factorized y-axis (not needed just for demonstration)
  2. a stacked bar putting ages into age ranges
import matplotlib.pyplot as plt

df = pd.read_csv(io.StringIO("""*Age* *RemoteWork*
18  Sometimes
24  Never
30  Sometimes
15  Never
24  Sometimes"""), sep="s+")


fig, ax = plt.subplots(1,2, figsize=[10,5],
                      sharey=False, sharex=False, gridspec_kw={"hspace":0.3})

(df
 .assign(a=lambda dfa: ((dfa["*Age*"]//10)*10).astype(str)+"-"+(((dfa["*Age*"]//10)*10)+9).astype(str))
 .groupby(["a","*RemoteWork*"])
 .agg("count")
 .unstack(0)
 .droplevel([0], axis=1)
 .plot(ax=ax[1],kind="bar", stacked=True)
)
ax[1].set_xlabel("Stacked", weight='bold', fontsize=12)


(df
 .assign(y=lambda dfa: pd.factorize(dfa["*RemoteWork*"])[0])
 .plot(ax=ax[0],kind="scatter", x="*Age*", y="y", c="*Age*", s="*Age*", colormap="jet")
)
ax[0].set_xlabel("Scatter", weight='bold', fontsize=12)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...