-2

I have a dataframe 'dft' with two columns 'Month' (can be January through to December) and 'Expenditure' for that month.

I am attempting to create a stacked bar chart for this data, with the stacks represnting expenditure between 0 - 100; 100 - 500 and 500+;

To sort the dataframe for these values I have written the following code.

small = dft[(dft['Expenditure'] < 100) & (dft['Expenditure'] > 0)]
medium = dft[(dft['Expenditure'] <= 500) & (dft['Expenditure'] >= 100)]
large = dft[(dft['Expenditure'] > 500)] 

Is there a way I can then plot these dataframes in a stacked bar chart straight from Pandas? The chart would have an x axis of Month and y axis of expenditure.

William
  • 141
  • 1
  • 9
  • 1
    Instead of splitting the dataframe, add a new column with the qualifier to stack (small, medium, large). Then pivot the frame by that new column and plot with [`stacked=True` option](https://pandas.pydata.org/pandas-docs/stable/visualization.html#bar-plots). – ImportanceOfBeingErnest Nov 09 '18 at 16:08

2 Answers2

1

I tried to create a simple example (using the original given data) which solves your case. You should also have a look at the stacked_bar_chart in the documentation. To convert the months and "fill up" the data you can use the following approach:

stacked bar chart

import numpy as np
import matplotlib.pyplot as plt

# given x data
x1 = ['January', 'October', 'November', 'December']
x2 = ['January', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
x3 = ['January', 'November', 'December']

# given y data
y1 = [2.0, 91.53, 16.7, 50.4]
y2 = [1240.3, 216.17, 310.77, 422.12, 513.53, 113.53, 377.249, 1179.41]
y3 = [15.6, 235.433, 574.45]

# save all months in a list
months = ['January',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December']

monthsDict = {}

# assign in a dictionary a number for each month
# 'January' : 0, 'February' : 1
for i, val in enumerate(months):
    monthsDict[val] = i


# this function converts the given datasets by you into full 12 months list
def to_full_list(x, y):

    # initialize a list of floats with a length of 12
    result = [0.0] * 12

    # assign for each months in the list the value to the corresponding index in result
    # x[0] = January, y[0] = 2.0 would be result[0] = 12.0
    for i, val in enumerate(x):
        result[monthsDict[val]] = y[i]

    return result


# convert the given data into the right format
r1 = np.array(to_full_list(x1, y1))
r2 = np.array(to_full_list(x2, y2))
r3 = np.array(to_full_list(x3, y3))

# increase the width of the output to match the long month strings
plt.figure(figsize=(11, 6))

# plot each of the created datasets
# x axis: months; y axis: values
p3 = plt.bar(months, r3 + r2 + r1)
p2 = plt.bar(months, r2 + r1)
p1 = plt.bar(months, r1)

# display the plot
plt.show()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
NiklasPor
  • 9,116
  • 1
  • 45
  • 47
  • @William The only value the data for december has is `1179.41`. Am I missing something important? Also I just realized, you delted your other question and created a new one. Oops. – NiklasPor Nov 09 '18 at 16:43
  • Thanks - This is partially correct although there seems to be an error in the stacking – William Nov 09 '18 at 16:44
  • December has 1179.41, 574.45 and 50.4. The months in x1 map directly to y1. So december in x1 maps to 50.4 in y1 – William Nov 09 '18 at 16:46
  • @William Sorry, I forgot to sum the values for r1, r2 and r3. Give me a second I'll edit the answer. – NiklasPor Nov 09 '18 at 16:58
0

Turning my comment into an answer: Instead of splitting the dataframe, add a new column with the qualifier to stack (small, medium, large). Then pivot the frame by that new column and plot with stacked=True option.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# some data
dft = pd.DataFrame({"month" : ['January', 'October', 'November', 'December', 'January',
                               'June', 'July', 'August', 'September', 'October',
                               'November', 'December', 'January', 'November', 'December'],
                    "expediture" : [2.0, 91.53, 16.7, 50.4, 1240.3, 216.17, 310.77, 422.12,
                                    513.53, 113.53, 377.249, 1179.41, 156, 2354.33, 157.45]})

# possible labels / months
labels = ['small', 'medium', 'large']
months = pd.date_range('2014-01','2014-12', freq='MS').strftime("%B").tolist()
full = pd.DataFrame(columns=labels, index=months)

#quantize data
dft["quant"] = pd.cut(dft["expediture"], bins = [0,100,500,np.inf], labels=labels)
# pivot data
piv = dft.pivot(values='expediture',  columns="quant",  index = "month")
# update full with data to have all months/labels available, even if not
# present in original dataframe
full.update(piv)

full.plot.bar(stacked=True)

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712