简体   繁体   中英

I am trying to plot three lines with matplotlib but it is showing up as one

I have a DF That I am using to plot how many userlogs a player has had in a given hour. I want to see what time of the day they are most active.

    username    hour    freq
0   Player 1    0        74
1   Player 1    1        37
2   Player 1    2        6
3   Player 2    3        152
4   Player 2    5        90
5   Player 2    6        57
6   Player 3    7        219
7   Player 3    8        443
8   Player 3    9        557

I then use that DF and try and plot it like this:

plt.rcParams['figure.figsize'] = 10,5
for name in playername: 
    playertimes = new_df[new_df.username.isin([name])]
    plt.plot(playertimes['freq'], c='Black', ls='--', marker = 's', ms=7, label = name)
plt.legend(loc='upper left', bbox_to_anchor=(1,1))
plt.xticks(list(range(0,24)), new_df['hour'], rotation = 'vertical')
plt.show()

My logic is that I am going to use the playertimes df as a temporary df so I can plot only the freq of each player.

I was hoping for one line for each player but what I got was this:

Failed Graph

I tried messing with a few things but can not seem to get it to work. Any ideas?

The list of users has to be unique to go through the dataframe just once, and the dataframe should be sorted by 'hour' to display the results as expected. In order to display the proper values on the x axis, you just need to actually plot those values on the x-axis. The code below includes all these changes:

plt.rcParams['figure.figsize'] = 10,5
linestyles = ['-', '--', ':']
markers = ['s', 'o', 'v']
for i, name in enumerate(df.username.unique()): 
    playertimes = df[df.username.isin([name])].sort_values('hour')
    plt.plot(playertimes['hour'], playertimes['freq'], c='Black', 
ls=linestyles[i], marker =markers[i], ms=7, label = name)
plt.legend(loc='upper left', bbox_to_anchor=(1,1))
plt.xticks(range(0,24), rotation = 'vertical')
plt.show()

3 个地块

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