简体   繁体   English

如何在条形图上划出x-ticks,并缩放y轴

[英]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 : 然后我使用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 我不确定如何做两件事:1)空出x轴的国家名称,使它们不相互交叉2)不同地缩放y轴,这样所有的分数似乎都不是这样的彼此接近

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. 另一种方法是为你的酒吧使用宽间距的x位置。 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. 编辑:为了完整起见,我添加了Rocky Li关于缩放y轴的建议。

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

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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