简体   繁体   中英

How to space out x-ticks on bar graph, and scale y-axis

I have the following code that creates a small dataframe of various countries and a corresponding score value:

import pandas
import numpy 
import matplotlib
import matplotlib.pyplot as plt
df = pandas.DataFrame(data = ["Norway", "Denmark", "Iceland", 
"Switzerland", "Finland", "Netherlands", "Canada", "New Zealand", 
"Sweden", "Australia"], columns = ["Countries"])
df["Score"] = [7.6, 7.55, 7.50, 7.45, 7.40, 7.35, 7.30, 7.25, 7.20, 
7.15]

I then create a bar graph using matplotlib :

bars = df['Countries']
height = df['Score']
plt.bar(bars, height, align = "center", alpha = 0.5)
plt.ylabel('Happiness Score')
plt.title('Happiness by Country')
plt.show

I am unsure on how to do 2 things: 1) space out the country names of the x-axis so that they are not crossing each other 2) scale the y-axis differently, so that all of the scores don't seem so close to each other

You can simply rotate the labels by some angle of your taste to avoid the overlap. Other way would be to use a widely spaced x-positions for your bars. However, since the country names are long and unequal in length, I wouldn't suggest this.

EDIT: For completeness sake, I am adding Rocky Li's suggestion for the scaling of the y-axis.

plt.xticks(rotation=45)
plt.ylim(7, 8)

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM