简体   繁体   中英

How to change y-axis limits on a bar graph?

I have a df , from which Ive indexed europe_n and Ive plotted a bar plot.

  • europe_n (r=5, c=45) , looks like this. ;
    在此处输入图像描述

  • df['Country'] ( string ) & df['Population'] ( numeric ) variable/s.

plt.bar(df['Country'],df['Population'], label='Population')
plt.xlabel('Country')  
plt.ylabel('Population')  
plt.legend()  
plt.show()

Which gives me;

在此处输入图像描述

Objective: Im trying to change my y-axis limit to start from 0 , instead of 43,094 .
I ran the, plt.ylim(0,500000) method, but there was no change to the y-axis and threw an error. Any suggestions from matplotlib library?

Error ; 在此处输入图像描述

ax.set_ylim([0,max_value])

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
df = pd.DataFrame({
    'Country':['Denmark', 'Finland', 'Iceland', 'Norway', 'Sweden'],
    'Population':[5882261, 5540745, 372899, 5434319, 10549347]
})
print(df)
###
   Country  Population
0  Denmark     5882261
1  Finland     5540745
2  Iceland      372899
3   Norway     5434319
4   Sweden    10549347
fig, ax = plt.subplots()
ax.bar(df['Country'], df['Population'], color='#3B4B59')
ax.set_title('Population of Countries')
ax.set_xlabel('Country')
ax.set_ylabel('Population')
max_value = 12000000
ticks_loc = np.arange(0, max_value, step=2000000)
ax.set_yticks(ticks_loc)
ax.set_ylim([0,max_value])
ax.set_yticklabels(['{:,.0f}'.format(x) for x in ax.get_yticks()])
ax.grid(False)
fig.set_size_inches(10,5)
fig.set_dpi(300)
plt.show()

在此处输入图像描述





Be sure that you already imported the following packages,

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

Your code should probably like:

fig, ax = plt.subplots()
ax.bar(europe_n['Country'].values, europe_n['Area(sq km)'].values, color='#3B4B59')
ax.set_xlabel('Country')
ax.set_ylabel('Population')
max_value = 500000
ticks_loc = np.arange(0, max_value, step=10000)
ax.set_yticks(ticks_loc)
ax.set_ylim(0,max_value)
ax.set_yticklabels(['{:,.0f}'.format(x) for x in ax.get_yticks()])
ax.grid(False)
fig.set_size_inches(10,5)
fig.set_dpi(300)
plt.show()

https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.ylim.html

To set the y limit

plt.ylim(start,end)

To set the x limit

plt.xlim(start,end)

Example在此处输入图像描述

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