user10346242
user10346242

Reputation: 11

Matplotlib 2 y axis with mean

Hi i have been trying to figure out how do i plot my data frame into the graphs. My dataframe looks like this .

Country | exports 2015 | exports 2016 | Gdp 2015 | GDP 2016| 
  A     |     500      |     600      |   34324  |  23525  | 
  B     |     435      |     335      |    3243  |   2324  |
  C     |     222      |     324      |    23423 |   1233  | 
  D     |     7756     |     9000     |    32424 |  65545  | 

Basically i want to compare the mean for all the columns and plot them on a graph with 1 x axis as the years and 2 y axis as the exports and GDP. I can only do for 1 year. Basically im trying to get

         |                                    |
         |                                    |
         |                                    |
 Mean    |                                    |
Exports  |                                    | Mean GDP
         |                                    |
         |                                    |
         |____________________________________|  
              2015                  2016

Do i need to somehow convert the data into a mean when plotting the graph or do i do another column? Any advice would be great thanks :)

Upvotes: 0

Views: 646

Answers (1)

An economist
An economist

Reputation: 1311

This is one possible solution, using pandas. The only difficulty is with setting the legend position, since you have to set labels for each y-axis. Keep in mind that double axis plots are very confusing.

import pandas as pd
import matplotlib.pyplot as plt


# Stacked input data 
df = pd.DataFrame({'Country': ['A','B', 'C', 'D','A','B', 'C', 'D'],
                   'Year': ['2015','2015','2015','2015','2016','2016','2016','2016'],
                   'Export': [500, 435, 222, 7756,600, 335, 324, 9000],
                   'GDP': [34324, 3243, 23423, 32424,23525, 2324, 1233, 65545]})

# Calculate yearly means
year_means = df.groupby('Year').mean().reset_index()

# Plot the means
ax = year_means.plot(x='Year',
                     y=['Export', 'GDP'],
                     secondary_y= 'GDP',
                     kind= 'bar',
                     mark_right=False)

#Set labels
ax.set_ylabel('Exports')
ax.right_ax.set_ylabel('GDP')

# Adjust legend position
ax.legend(bbox_to_anchor=(1,1), loc="upper left")
ax.right_ax.legend(bbox_to_anchor=(1.2,1), loc="upper left")

plt.show()

enter image description here

EDIT: OP does not have stacked input data. One way to fix it is to transform variables individually and then combine them into single frame. Below solution is far from optimal.

# Not stacked input data 
df = pd.DataFrame({'Country': ['A','B', 'C', 'D'],
                   'Export 2015': [500, 435, 222, 7756],
                   'Export 2016': [600, 335, 324, 9000],
                   'GDP 2015': [34324, 3243, 23423, 32424],
                   'GDP 2016': [23525, 2324, 1233, 65545]})


def stack_variable(df, variable):

    # Get columns of the input dataframe
    names = df.columns

    # Get column names with variable of interest
    var_columns = [name for name in names if variable in name]

    # Extract years
    years = [y.split(variable + ' ')[1] for y in var_columns]

    # Empty dataframe to store results
    stacked_df = pd.DataFrame(columns = [variable, 'Year'])

    # Fill the empty frame
    for idx, col in enumerate(var_columns):
             current = pd.DataFrame({variable: df[col],
                                     'Year': years[idx]})

             stacked_df = stacked_df.append(current)



    return stacked_df


exports = stack_variable(df, 'Export')
gdp = stack_variable(df, 'GDP')

stacked_df = pd.concat([exports, gdp['GDP']], axis=1).reset_index(drop=True)

Which would return:

stacked_df

       Export   Year    GDP
    0   500     2015    34324
    1   435     2015    3243
    2   222     2015    23423
    3   7756    2015    32424
    4   600     2016    23525
    5   335     2016    2324
    6   324     2016    1233
    7   9000    2016    65545

Upvotes: 1

Related Questions