0

I was able to find this very useful code snip here: https://stackoverflow.com/a/11250884/17621447

That code allows you to replace any xtick in the xaxis with a new string. Works great, but currently my code cant access fig and not sure how to re-write it in order to integrate that code snip.

Here is my current code:

ax = percentage_type_max_df.plot(figsize=(5, 5))
plt.show()

I think I don't fully understand what fig is doing. How can I rewrite the above code in order to introduce this line of code:

fig.canvas.draw()

labels = [item.get_text() for item in ax.get_xticklabels()]
labels[1] = 'Testing'

ax.set_xticklabels(labels)

plt.show()

Please help

Jack_xch
  • 5
  • 1
  • 6

1 Answers1

0

you have to create an axes object, then plot the dataframe on it. This will then allow you to access the axes object before/after, and do whatever you want:

import pandas as pd
import matplotlib.pyplot as plt

#some arbitrary dataframe
df = pd.DataFrame({'x':[100,200], 'y':[200,300]})
fig, ax = plt.subplots()
df.plot(ax=ax)

#now edit the tick labels
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = 'Testing'
ax.set_xticklabels(labels)

enter image description here

Derek Eden
  • 4,403
  • 3
  • 18
  • 31
  • Thanks! Yes this all works well. When I use the code I get back this error: ```UserWarning: FixedFormatter should only be used together with FixedLocator ax.set_xticklabels(labels)```. Also how do I create multiple ax,figs? I have other graph that is similar but a subset of it. Tried fig2, ax2 = plt,subplot() but this was not accepted. I want my code to generate two graphs at once. – Jack_xch Dec 08 '21 at 04:07
  • Also this is a bit unrelated but I do you by chance know why: ```ax = df.plot(figsize=(5, 5), path_effects=[path_effects.SimpleLineShadow(), path_effects.Normal()])``` produces the graph with the path effect shadow but when I use:```fig, ax = plt.subplots(figsize=(5, 5), linewidth=4, path_effects=[path_effects.SimpleLineShadow(), path_effects.Normal()])``` it does not? – Jack_xch Dec 08 '21 at 05:37
  • im not sure, but im guessing because df.plot actually plots the data in the dataframe, where plt.subplots just makes an empty plot... theres nothing to apply the path effects to – Derek Eden Dec 26 '21 at 01:16