import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

Import your data

df = pd.read_csv("../country-gdp-2014.csv")
df.head()
Country Continent GDP_per_capita life_expectancy Population
0 Afghanistan Asia 663 54.863 22856302
1 Albania Europe 4195 74.200 3071856
2 Algeria Africa 5098 68.963 30533827
3 Angola Africa 2446 45.234 13926373
4 Antigua and Barbuda N. America 12738 73.544 77656

Specify axis labels with pandas

When you plot, you get back an ax element. It has a million and one methods, two of which are set_xlabel and set_ylabel.

# Draw a graph with pandas and keep what's returned
ax = df.plot(kind='scatter', x='GDP_per_capita', y='life_expectancy')

# Set the x scale because otherwise it goes into weird negative numbers
ax.set_xlim((0, 70000))

# Set the x-axis label
ax.set_xlabel("GDP (per capita)")

# Set the y-axis label
ax.set_ylabel("Life expectancy at birth")
<matplotlib.text.Text at 0x10891db00>

png

Specify axis labels with matplotlib

Just to mix it up a bit, this time we’re going to use plt.subplots() to create a figure first. When we pull the GDP and life expectancy out of the dataframes they just look like lists to the matplotlib plotter.

# Initialize a new figure
fig, ax = plt.subplots()

# Draw the graph
ax.plot(df['GDP_per_capita'], df['life_expectancy'], linestyle='', marker='o')

# Set the label for the x-axis
ax.set_xlabel("GDP (per capita)")

# Set the label for the y-axis
ax.set_ylabel("Life expectancy at birth")
<matplotlib.text.Text at 0x108170a90>

png