Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

matplotlib - controlling the number of x ticks in pyplot

I want to display all 13 x ticks, but the graph only shows 7 of them having two intervals.

plt.locator_params(axis='x',nbins=13)

Why doesn't above code work??

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as dates

y = [0, 0.86, 0.826, 0.816, 0.807, 0.803, 0.804, 0.803, 0.802,0.81, 0.813, 0.813, 0.813]

times = pd.date_range('2015-02-25', periods=13)
fig, ax = plt.subplots(1)
fig.autofmt_xdate()

xfmt = dates.DateFormatter('%d-%m-%y')
ax.xaxis.set_major_formatter(xfmt)

plt.locator_params(axis='x',nbins=13)

ax.plot_date(times.to_pydatetime(), y, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                            interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d
%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
plt.tight_layout()
plt.show()

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The warning should give you some clue why this is happening:

UserWarning: 'set_params()' not defined for locator of type <class 'pandas.tseries.converter.PandasAutoDateLocator'>
  str(type(self)))

Use plt.xticks(times.to_pydatetime()) instead:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as dates

y = [0, 0.86, 0.826, 0.816, 0.807, 0.803, 0.804, 0.803, 0.802,0.81, 0.813, 0.813, 0.813]

times = pd.date_range('2015-02-25', periods=13)
fig, ax = plt.subplots(1)
fig.autofmt_xdate()

xfmt = dates.DateFormatter('%d-%m-%y')
ax.xaxis.set_major_formatter(xfmt)


ax.plot_date(times.to_pydatetime(), y, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                            interval=1))
plt.xticks(times.to_pydatetime())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d
%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
plt.tight_layout()
plt.show()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...