Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting y-axis matplotlib with thousands separator and font size

The code below works.

names = years 1960 - 2016

values = GDP of the US for each year

The code produces two charts, but the y-axis label runs from 5000 to 175000. I want to 1) format the label with a "," for a thousands separator, so as an example, 5,000 or 17,500, and,

2) I want to increase the font size of the labels - so increase the font of, for example, 5000.

Not finding a workable/understandable example on line. Help appreciated.

%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
from numpy import array

# Plot GDP/Year

names =  usa.loc[: , "Year"]
values = usa.loc[: , "GDP Billions"]

plt.figure(1, figsize=(15, 6))
plt.suptitle('GDP Growth', fontsize=20)

plt.subplot(121)
plt.plot(names, values)
plt.xticks(np.arange(0, 57, step=5.0))
plt.ylabel('GDP', fontsize=16)
plt.title('United States',fontsize=16)

plt.subplot(122)
plt.plot(names, values)
plt.xticks(np.arange(0, 57, step=5.0))
plt.xlabel('Year', fontsize=16)
plt.title('United States',fontsize=16)

#plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 4))
#print(plt.xticks())


plt.show()
like image 603
user3504322 Avatar asked Aug 07 '18 19:08

user3504322


1 Answers

1) format the label with a "," for a thousands separator, so as an example, 5,000 or 17,500, and (as in How do I format axis number format to thousands with a comma in matplotlib?)

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.get_yaxis().set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))

2) I want to increase the font size of the labels - so increase the font of, for example, 5000:

plt.rc('ytick', labelsize=5000) 

Here's how you change your code to incorporate these solutions (as requested in the comment):

%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
from numpy import array

plt.rc('ytick', labelsize=12) 

# Plot GDP/Year
names =  usa.loc[: , "Year"]
values = usa.loc[: , "GDP Billions"]


fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))

fig.suptitle('GDP Growth', fontsize=20)

ax1.plot(names, values)
ax1.set_xticklabels(np.arange(0, 57, step=5.0))
ax1.set_ylabel('GDP', fontsize=16)
ax1.set_title('United States',fontsize=16)
ax1.get_yaxis().set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))

ax2.plot(names, values)
ax2.set_xticklabels(np.arange(0, 57, step=5.0))
ax2.set_ylabel('Year', fontsize=16)
ax2.set_title('United States',fontsize=16)
ax2.get_yaxis().set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
#plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 4))
#print(plt.xticks())


plt.show()

And here's what the plots look like for a dummy data I created: enter image description here

like image 153
Peybae Avatar answered Sep 18 '22 11:09

Peybae