Installing xticks in pandas string

I ran into this different behavior in the third example below. Why can I edit the x-axis checkmarks correctly with c pandas

line()

and area()

graphs but not c bar()

? What's the best way to fix the (common) third example?

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

x = np.arange(73,145,1)
y = np.cos(x)

df = pd.Series(y,x)
ax1 = df.plot.line()
ax1.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax1.xaxis.set_minor_locator(ticker.MultipleLocator(2.5))
plt.show()

ax2 = df.plot.area(stacked=False)
ax2.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax2.xaxis.set_minor_locator(ticker.MultipleLocator(2.5))
plt.show()

ax3 = df.plot.bar()
ax3.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax3.xaxis.set_minor_locator(ticker.MultipleLocator(2.5))
plt.show()

      

+3


source to share


1 answer


Problem:

The hatch plot is intended for use with categorical data. Therefore, the bars are not actually in positions x

, but in positions 0,1,2,...N-1

. The bar labels are then adjusted to values x

.
If you then place a check mark on only every tenth bar, a second check mark will be placed on the tenth bar, etc. The result will be

enter image description here

You can see that the bars are actually positioned with integer values ​​starting at 0 using the usual ScalarFormatter on the axes:

ax3 = df.plot.bar()
ax3.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax3.xaxis.set_minor_locator(ticker.MultipleLocator(2.5))
ax3.xaxis.set_major_formatter(ticker.ScalarFormatter())

      

enter image description here

Now you can of course define your own fixed formatter like this



n = 10
ax3 = df.plot.bar()
ax3.xaxis.set_major_locator(ticker.MultipleLocator(n))
ax3.xaxis.set_minor_locator(ticker.MultipleLocator(n/4.))
seq =  ax3.xaxis.get_major_formatter().seq
ax3.xaxis.set_major_formatter(ticker.FixedFormatter([""]+seq[::n]))

      

enter image description here

which has a disadvantage that starts with some arbitrary value.

Decision:

I would suggest that the best general solution is not to use the pandas plot function at all (which is just a wrapper anyway), but the matplotlib function bar

directly:

fig, ax3 = plt.subplots()
ax3.bar(df.index, df.values, width=0.72)
ax3.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax3.xaxis.set_minor_locator(ticker.MultipleLocator(2.5))

      

enter image description here

+2


source







All Articles