rotating xticks in seaborn scatterplot

Question:

i have an aggregate dataset that i am trying to visualise, it looks like that:

enter image description here

and i need to plot some statistics for 18 states. currently the plot looks in the following way:

enter image description here

and i manage to set xticks with the following code, however there is no rotate and i get an error. the code for the plot is:

fig, ax = plt.subplots(figsize = (15, 6))
sns.scatterplot(ax = ax, x = 'state', y = 'price per acre, usd', data = data)
ax.set_xlabel("state", size = 12)
ax.set_ylabel('average price per acre of land, usd', size = 12)
ax.set_title('average prices on industrial land', size = 20)
ax.set_xticklabels(data['state'], rotation = 45)
plt.show()

and the error i get looks like this:

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:
-> 3363                 raise KeyError(key) from err
   3364 
   3365         if is_scalar(key) and isna(key) and not self.hasnans:

KeyError: 'state'

so how i can rotate those labels (with names of states in the plot so that i do not receive an error and got a visually nice plot)? the column with the names of the state is called "state" as it is clearly from the plot code

Asked By: ela rednax

||

Answers:

thanks to stef we found out that the name of the column i was trying to use was actually an index, so i’ve modified the line to look for those state names in the index and it worked:

ax.set_xticklabels(data.index, rotation = 45)
Answered By: ela rednax

If you want to change the tick parameters, e.g. the rotation, use set_tick_params instead of re-setting the labels along with the rotation:

ax.xaxis.set_tick_params(rotation = 45)
Answered By: Stef