简体   繁体   中英

Plot 350 users on bar chart using matplotlib

I'm trying to plot around 300 users and how many purchases they have made. My data is in a pandas dataframe, where the column 'ID' refers to a user and 'Number' to the number of purchases.

I have tried so far with the following code I have found but never manage to get all the IDs on one plot?

This is the code:

import random
# Prepare Data

n = subs_['Number'].unique().__len__()+1
all_colors = list(plt.cm.colors.cnames.keys())
random.seed(100)
c = random.choices(all_colors, k=n)

# Plot Bars
plt.figure(figsize=(16,10), dpi= 60)
plt.bar(subs_['ID'], subs_['Number'], color=c, width=.5)
for i, val in enumerate(subs_['Number'].values):
    plt.text(i, val, float(val), horizontalalignment='center', verticalalignment='bottom', fontdict={'fontweight':500, 'size':10})

# Decoration
plt.gca().set_xticklabels(subs_['ID'], rotation=60, horizontalalignment= 'right')
plt.title("Number of purchases by user", fontsize=22)
plt.ylabel('# Purchases')
plt.ylim(0, 45)
plt.show()

bar chart of user purchases:

用户购买条形图

I think that your problem is coming from your IDE:

import random
import matplotlib.pyplot as plt
import pandas as pd
# Prepare Data

d = {'ID': range(1, 300), 'Number': range(1, 300)}
subs_ = pd.DataFrame(data=d)
n = subs_['Number'].unique().__len__()+1
all_colors = list(plt.cm.colors.cnames.keys())
random.seed(100)
c = random.choices(all_colors, k=n)

# Plot Bars
plt.figure(figsize=(16,10), dpi= 60)
plt.bar(subs_['ID'], subs_['Number'], color=c, width=.5)
for i, val in enumerate(subs_['Number'].values):
    plt.text(i, val, float(val), horizontalalignment='center', verticalalignment='bottom', fontdict={'fontweight':500, 'size':10})

# Decoration
plt.gca().set_xticklabels(subs_['ID'], rotation=60, horizontalalignment= 'right')
plt.title("Number of purchases by user", fontsize=22)
plt.ylabel('# Purchases')
plt.ylim(0, 45)
plt.show()

Is working fine for me:

绘图输出

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