Python Matplotlib: how to reduce number of x tick marks for non-numeric tyoe

两盒软妹~` 提交于 2021-01-28 22:10:23

问题


I have this very simple pandas dataframe here and i'm trying to plot the index column (Date, which is formatted as string) against 'Adj Close' Column.

            Adj Close
      Date                  
2010-01-01  1.438994
2010-01-04  1.442398
2010-01-05  1.436596
2010-01-06  1.440403
2010-01-07  1.431803
... a lot more rows

Here's my very simple code:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(df['Adj Close'], label='Close Price History')
fig.autofmt_xdate()

however the graph is unpleasant in the sense that there are too many overlapping x ticks.

I've tried out the solution here using the code

ax.locator_params(axis='x',nbins=10)

I thought this would give me 11 ticks with 10 equally spaced interval in between. However the I've gotten an error:

/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:4: UserWarning: 'set_params()' not defined for locator of type <class 'matplotlib.category.StrCategoryLocator'> after removing the cwd from sys.path.

I have no idea what the error means, guess it's because my x-axis is in string format (non-numeric)? Just to emphasis, i'm really seeking for simple solution to solve this problem, not interested to format the column as date and go though all the hardship in date manipulation. Just assuming my x ticks are strings and there's no way to apply numeric calculation on them, is it possible to just reduce the frequency of x ticks shown to get a more visually appealing plot?


回答1:


You can sample your ticks and set the list as your new ticks.

# current x labels
current_ticks = ax.get_xticklabels()
# resampling every other label, change mod(2) to sample less
custom_ticks = [a.get_text() for a in current_ticks if current_ticks.index(a)%2] 
# set as new labels
ax.set_xticks(custom_ticks)
ax.set_xticklabels(custom_ticks)


来源:https://stackoverflow.com/questions/60520123/python-matplotlib-how-to-reduce-number-of-x-tick-marks-for-non-numeric-tyoe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!