Home > Enterprise >  Barplot/Histogram with matplotlib/seaborn
Barplot/Histogram with matplotlib/seaborn

Time:06-02

I am trying to achieve a simple barplot/histogram, however, the output is empty:

df = pd.DataFrame()

df["Subject_Age"] = X["Subject.Age"]

bins = [0, 15, 25, 35, 45, 55, 65, 75, 100]

labels = ['0 - 15', '16 - 25', '26 - 35', '36 - 45', '46 - 55', '56 - 65', '66 - 75', '76 ']

binned_values = np.histogram(df['Subject_Age'], bins=bins)[0].tolist()

df_hist = pd.DataFrame.from_dict(dict(zip(labels, binned_values)), orient='index').reset_index()

binned_values = np.histogram(df['Subject_Age'], bins=bins)[0].tolist()

df_hist = pd.DataFrame.from_dict(dict(zip(labels, binned_values)), orient='index').reset_index()

df_hist.columns = ['Age range', 'Counts']

sn.barplot(data = df, x = 'Age range', y = 'Counts', palette = 'rocket',
           ci = 'sd', 
order = ['0-15', '16-25', '26-35', '36-45', '46-55', '56-65', '66-75', '76 ']);

Which results in an empty barplot:

Output

Thanks in advance for your input!

CodePudding user response:

Try this one:

import pandas as pd

bins = [0, 15, 25, 35, 45, 55, 65, 75, 100]
labels = ['0 - 15', '16 - 25', '26 - 35', '36 - 45', '46 - 55', '56 - 65', '66 - 75', '76 ']

df = pd.DataFrame()
# Data example
df['Age'] = [5, 10, 12, 18, 23, 26, 27, 28, 36, 46, 47, 49, 50, 55, 56, 57, 58, 59, 60, 67, 67, 80, 89, 89, 88, 91]

df_count = pd.cut(df['Age'], bins=bins, labels=labels).value_counts(sort=False)
df_count.plot.bar(y='Age', use_index=True).figure.show()
  • Related