JacobMarlo
JacobMarlo

Reputation: 87

Problem with stacked area chart, keeps showing up percent stacked area chart?

So I've spent about 10 hours on this simple task already, I'm out of patience. I'm unable to get the chart I want.

What I want:

enter image description here

What I get:

enter image description here

Yes I am using percentages, but I do not want my chart to be full, I just want the percentages to be stacked one on top of eachother.

My code:

plt.figure()
plt.stackplot(unique_years, my_percentages[:, 0], my_percentages[:, 1],my_percentages[:, 2], labels=['Petrol','Diesel', 'Hybrid'])
plt.legend(loc='upper left')
plt.show()

The my_percentage is a numpy table with 3 columns named 0,1 and 2, each representing a type of fuel as a percentage.

Unique_years is an array for each unique year (1997-2020).

Can anybody please help? I am desperate lol

Upvotes: 0

Views: 286

Answers (1)

JohanC
JohanC

Reputation: 80339

You need to put the three lists into a list:

from matplotlib import pyplot as plt
import numpy as np

unique_years = np.arange(1997, 2021)
my_values = np.random.rand(len(unique_years), 5)
my_percentages = 100 * my_values / my_values.sum(axis=1, keepdims=True)
plt.stackplot(unique_years, [my_percentages[:, 0], my_percentages[:, 1], my_percentages[:, 2]])
plt.show()

stackplot with 3 lists

Or you could just transpose the percentages array:

from matplotlib import pyplot as plt
from matplotlib.ticker import PercentFormatter
import numpy as np

unique_years = np.arange(1997, 2021)
my_values = np.random.rand(len(unique_years), 5)
my_percentages = 100 * my_values / my_values.sum(axis=1, keepdims=True)
plt.stackplot(unique_years, my_percentages.T[:3], labels=['fuel a', 'fuel b', 'fuel c'], colors=plt.cm.Set2.colors[:3])
plt.margins(x=0)
plt.gca().yaxis.set_major_formatter(PercentFormatter(100))
plt.legend(loc='upper left', bbox_to_anchor=[1.02, 1.02])
plt.tight_layout()
plt.show()

stackplot with transposed array

Upvotes: 1

Related Questions