1

For this question, I was provided the following information. enter image description here

enter image description here

Data in code form:

order_data = {'Alice': {5: 'chocolate'},
              'Bob': {9: 'vanilla'},
              'Clair': {7: 'strawberry'},
              'Drake': {10: 'chocolate' },
              'Emma': {82: 'vanilla'},
              'Alice': {70: 'strawberry'},
              'Emma': {42: 'chocolate'},
              'Ginger': {64: 'strawberry'} }

I was asked to make a bar graph detailing this data. The bar graph and the code used to make it using Altair is provided below.

import altair

data = altair.Data(customer=['Alice', 'Bob', 'Claire', 'Drake', 'Emma','Alice', 'Emma', 'Ginger'],
    cakes=[5,9,7,10,82,70,42,64],
    flavor=['chocolate', 'vanilla', 'strawberry','chocolate','vanilla','strawberry','chocolate','strawberry'])
chart = altair.Chart(data)
mark = chart.mark_bar()
enc = mark.encode(x='customer:N',y='cakes',color='flavor:N')
enc.display()

Graph: enter image description here

My question is: What is the best way to go about constructing this graph using matplotlib?

I know this isn't an unusual graph per say but it is unusual in the sense that I have not found any replications of this kind of graph. Thank you!

2 Answers 2

2

It has already been answered, but you can also graph it in pandas.plot.

import pandas as pd
data = pd.DataFrame({'customer':['Alice', 'Bob', 'Claire', 'Drake', 'Emma','Alice', 'Emma', 'Ginger'],
    'cakes':[5,9,7,10,82,70,42,64],
    'flavor':['chocolate', 'vanilla', 'strawberry','chocolate','vanilla','strawberry','chocolate','strawberry']})
df = pd.DataFrame(data)
df = df.pivot(index='customer',columns='flavor', values='cakes').fillna(0)
df.plot(kind='bar', stacked=True)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

Here is a reproduction of the Altair graph with Matplotlib. Note that I had to modify the order_data dictionary because a dict cannot be defined with multiple keys at once (so I had to group the dictionary by key values). Also note that some optionally styling statements are included to also mimic the style of Altair.

The trick is to use the bottom keyword argument of the ax.bar function. The following image is obtained from the code below.

bar stack altair like

import matplotlib.pyplot as plt

# data
order_data = {
    "Alice": {"chocolate": 5, "strawberry": 70},
    "Bob": {"vanilla": 9},
    "Clair": {"strawberry": 7},
    "Drake": {"chocolate": 10},
    "Emma": {"chocolate": 42, "vanilla": 82},
    "Ginger": {"strawberry": 64},
}

# init figure
fig, ax = plt.subplots(1, figsize=(2.5, 4))
colors = {"chocolate": "C0", "strawberry": "C1", "vanilla": "C2"}

# show a bar for each person
for person_id, (name, orders) in enumerate(order_data.items()):
    quantities = 0
    for order_id, (order, quantity) in enumerate(orders.items()):
        ax.bar(person_id, quantity, bottom=quantities, color=colors[order])
        quantities += quantity

# add legend
ax.legend([color for color in colors], bbox_to_anchor=(2.0, 1.0))

# remove top/right axes for style match
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.grid(axis="y", zorder=-1)

# ticks
ax.set_xticks(range(len(order_data)))
ax.set_xticklabels([name for name in order_data], rotation="vertical")

2 Comments

Is there anyway separate entries with the same customer may be placed on the same bar in the chart? For example say I had Emma purchase x amount of chocolate cakes, Alice purchases x amount of cakes, and then Emma comes back and purchases x amount of vanilla cakes. Is there anyway to have Emma's second purchase automatically be added to her existing data point on the chart without having to reorganize order_data so that her second order is included as a key value of her already existing location in the data? Thanks!
I think what you are looking for is group dictionary by keys with a defaultdict so you can create a new plot with the newly added data. If you want to do it in a real update (animated) way, you should have a look at creating animations with Matplotlib.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.