The following code (obtained from here):
JavaScript
x
33
33
1
import matplotlib.pyplot as plt
2
import pandas as pd
3
4
5
# Prepare Data
6
df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")
7
x = df.loc[:, ['mpg']]
8
df['mpg_z'] = (x - x.mean())/x.std()
9
df['colors'] = ['red' if x < 0 else 'darkgreen' for x in df['mpg_z']]
10
df.sort_values('mpg_z', inplace=True)
11
df.reset_index(inplace=True)
12
13
# Draw plot
14
plt.figure(figsize=(14,16), dpi= 80)
15
plt.scatter(df.mpg_z, df.index, s=450, alpha=.6, color=df.colors)
16
for x, y, tex in zip(df.mpg_z, df.index, df.mpg_z):
17
t = plt.text(x, y, round(tex, 1), horizontalalignment='center',
18
verticalalignment='center', fontdict={'color':'white'})
19
20
# Decorations
21
# Lighten borders
22
plt.gca().spines["top"].set_alpha(.3)
23
plt.gca().spines["bottom"].set_alpha(.3)
24
plt.gca().spines["right"].set_alpha(.3)
25
plt.gca().spines["left"].set_alpha(.3)
26
27
plt.yticks(df.index, df.cars)
28
plt.title('Diverging Dotplot of Car Mileage', fontdict={'size':20})
29
plt.xlabel('$Mileage$')
30
plt.grid(linestyle='--', alpha=0.5)
31
plt.xlim(-2.5, 2.5)
32
plt.show()
33
Gives me this:
What I’m trying to do is reduce the empty space on the y-axis, indicated here by the red bars:
How can I do this? Changing the height of the figure doesn’t seem to help.
Advertisement
Answer
One quick solution is to manually set the margins using
JavaScript
1
3
1
plt.margins(y=0) # no margin at all
2
plt.margins(y=1/len(df)) # equal margin
3