简体   繁体   中英

Plotting line plot with groupby in matplotlib/seaborn?

I have the following dataset (abbreviated, but still conveys the same idea). I want to show how user score changes over time (the postDate conveys time). The data is also presorted by postDate . The hope is to see a nice plot (perhaps using seaborn if possible) that has the score as the y-axis, time as the x-axis, and shows the users' scores over time (with a separate line for each user). Do I need to convert the postDate (currently a string) to another format in order to plot nicely? Thank you so much!

userID   postDate                                userScore (1-10 scale)
Mia1     2017-01-11 09:07:10.616328+00:00        8
John2    2017-01-17 08:05:45.917629+00:00        6
Leila1   2017-01-22 07:47:67.615628+00:00        9
Mia1     2017-01-30 03:45:50.817325+00:00        7
Leila    2017-02-02 06:38:01.517223+00:00        10

Based on the sample data you show your postDate series is already pandas datetime values. So to plot with dates on the X axis the key in matplotlib is to use plot_date , not plot. Something like this:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

for key, g in df.groupby['userID']:
    ax.plot_date(g['postDate'], g['userScore'], label=key)

ax.legend()

I've used plotly before, it's a really nice option to do interactive visualizations if you are using Jupyter Notebook. You generate htmls or plot inline in Jupyter with cufflinks. It's only paid for hosting your graphs somewhere but I use it for free for my own data analysis.

Install plotly and also cufflinks, cufflinks helps out to do plots almost instantly with pandas dfs.

For example you could do:

your_df.iplot(x='postDate', y='userScore')

this will automatically give you the 'time-series' you describe.

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