0

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

9
  • What is the output of print(data.columns) inserted right before ax.set_xticklabels? Commented Jun 27, 2022 at 13:24
  • it's Index(['price', 'square, ac', 'price per acre, usd'], dtype='object') Commented Jun 27, 2022 at 13:30
  • so where is your state column here? Commented Jun 27, 2022 at 13:30
  • i do not know, probably it is not here because it is the index, as this dataframe was received after groupping the bigger dataframe by state. i will now edit the question and insert the table that i am trying to plot. and anyway the plot did insert state names from somewhere in the x-axis labels Commented Jun 27, 2022 at 13:39
  • 1
    state is now the index, what if you do ax.set_xticklabels(data.index, rotation = 45)? Commented Jun 27, 2022 at 13:41

2 Answers 2

0

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) 
Sign up to request clarification or add additional context in comments.

Comments

0

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) 

1 Comment

please see my answer for a better way to do it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.