Issue
I created a single stacked horizontal bar chart which illustrates the values in a (normalized) series using:
data = df['state'].value_counts(normalize=True).to_frame()
data.T.plot.barh(stacked=True, figsize=(18,3))
which produced the following output:
I'd like to arrange the legend labels into a few columns and display them below the x-axis. How can I accomplish this?
Solution
You can call plt.legend(...)
setting the number of columns and the legend's position. This will erase the existing legend and create it again.
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
states = ["Avaloria", "Eldoria", "Mystara", "Zephyria", "Nimoria", "Dragoria", "Frostvale", "Solaris", "Thundara",
"Luminara", "Shadowmere", "Celestia", "Aquaria", "Pyronia", "Galewind", "Starfell", "Moonhaven", "Ironforge"]
prob = np.random.rand(len(states)) ** 2 + 0.05
prob /= prob.sum()
df = pd.DataFrame({'state': np.random.choice(states, 500, p=prob)})
data = df['state'].value_counts(normalize=True).to_frame()
data.T.plot.barh(stacked=True, figsize=(15, 3))
plt.legend(ncol=6, loc='upper left', bbox_to_anchor=(0, -0.11))
plt.tight_layout()
plt.show()
Answered By - JohanC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.