Issue
From pandas documentation on creating pie charts from data frames:
I have the following code:
df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],
'radius': [2439.7, 6051.8, 6378.1]},
index=['Mercury', 'Venus', 'Earth'])
plot = df.plot.pie(y='mass', figsize=(5, 5))
This create a pie chart of planets by mass:
Now I add an argument in the plotting line to specify I want to use a specific Seaborn color palette "Set2":
df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],
'radius': [2439.7, 6051.8, 6378.1]},
index=['Mercury', 'Venus', 'Earth'])
plot = df.plot.pie(y='mass', figsize=(5, 5), colors=sns.color_palette('Set2'))
And we get the same plot, but now with a different color palette used:
When I run each of these code chunks, with each color palette, the color mapping with the planet names remains the same, telling me that the mapping is based on the value assigned to each planet name.
What I want to do is "grab" that mapping as a dictionary, such that it can be used in a for loop.
To explain the goal here, I have a data frame containing many different mass values assigned to each planet, from different analyses. This means that experiment "A" had these specific mass values for our three planets here, and experiment "B" had different values for the three planets, and experiment "C" had another different set of values of the three planets, etc. Each of the dataframes with these experiment values are generated from a for loop, iterating through each experiment. For each experiment I want to create a pie chart with the mass values. The main point here, is that I want all of the color mappings for the planets to be the same for each generated plot in the for loop. And so the idea is to "grab" the color mapping dictionary from the first iteration of the for loop, and then apply that exact color mapping to each following iteration of the for loop, assuming there will always just be three planets in the experiment. How can I do this, specifically getting that color mapping dictionary from the first iteration?
Solution
You can define the mapping as a dictionary and then define the plot colors as an array.
df = pd.DataFrame({
'mass': [0.330, 4.87 , 5.97],
'radius': [2439.7, 6051.8, 6378.1]
},
index=['Mercury', 'Venus', 'Earth'])
color_mapping = dict(zip(df.index, sns.color_palette('Set2')))
# this could be executed in a loop...
plot_colors = [color_mapping[planet] for planet in df.index]
plot = df.plot.pie(y='mass', figsize=(5, 5), colors=plot_colors)
Answered By - Keegan Kozler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.