Search code examples
pythonpandasmatplotlibgeopandas

Geopandas cannot remove axis and set title simultaneously


I have a geopandas dataframe and I am plotting chloropheth maps no problem. However, when I want to customise the map, by removing the axis and setting a title, I can only seem to do one or the other.

ax = world.plot(column = 'Inflation, consumer prices (annual %)',figsize = (15, 12), 
                      legend = True, legend_kwds={'shrink': 0.3},
                      missing_kwds = {'color' : 'lightgrey'}).set_title('title')

Works and sets a title. If I try to remove the axis instead;

ax = world.plot(column = 'Inflation, consumer prices (annual %)',figsize = (15, 12), 
                      legend = True, legend_kwds={'shrink': 0.3},
                      missing_kwds = {'color' : 'lightgrey'}).set_axis_off()

Also works. However if I try,

ax = world.plot(column = 'Inflation, consumer prices (annual %)',figsize = (15, 12), 
                      legend = True, legend_kwds={'shrink': 0.3},
                      missing_kwds = {'color' : 'lightgrey'}).set_title('title').set_axis_off()

I get the error telling me "AttributeError: 'Text' object has no attribute 'set_axis_off'". If I swap them around, setting axis off first then set title;

ax = world.plot(column = 'Inflation, consumer prices (annual %)',figsize = (15, 12), 
                      legend = True, legend_kwds={'shrink': 0.3},
                      missing_kwds = {'color' : 'lightgrey'}).set_axis_off().set_title('title')

It tells me "AttributeError: 'NoneType' object has no attribute 'set_title'".

I then tried first just doing one then later editing via;

ax = world.plot(column = 'Inflation, consumer prices (annual %)',figsize = (15, 12), 
                      legend = True, legend_kwds={'shrink': 0.3},
                      missing_kwds = {'color' : 'lightgrey'}).set_axis_off()
ax.set_title('title')

But this threw up the same error.

I am guessing it is something to do with 'what' my variable is, and how if I follow one augmentation with the other it thinks I am augmenting the previous argument? But I am reasonably new to geopandas, so any help would be greatly appreciated!


Solution

  • Don't assign a variale as the set_title and set_axis_off because it does not return a axis. you can do this instead.

    ax = world.plot(column = 'Inflation, consumer prices (annual %)',figsize = (15, 12), 
                          legend = True, legend_kwds={'shrink': 0.3},
                          missing_kwds = {'color' : 'lightgrey'})
    ax.set_axis_off()
    ax.set_title('title')
    plt.show()
    

    Here see that .set_title() returns a text.