0

Please consider the two plots generated by the following script. The line plot is incorrectly positioned in fig2.

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

np.random.seed(0x5eed)

arr1 = np.random.randint(5, 10, 4)
arr2 = np.random.randint(15, 20, 4)
idx = [1, 3, 4, 5]
kwargs = {'marker': 'o', 'color': 'C1'}

fig1, ax11 = plt.subplots()
ax12 = ax11.twinx()
ax11.bar(idx, arr1)
ax12.plot(idx, arr2, **kwargs)
fig1.savefig('fig1.png')

df = pd.DataFrame({'foo': arr1, 'bar': arr2}, index=idx)
fig2, ax21 = plt.subplots()
ax22 = ax21.twinx()
df['foo'].plot.bar(ax=ax21)
df['bar'].plot.line(ax=ax22, **kwargs)
fig2.savefig('fig2.png')

fig1 (expected):

fig1

fig2 (unexpected):

fig2

After some investigation, I found the following conditions to reproduce this problem.

  • Both bar chart and line plot are used (fig2 is correct if both plots are line plots)
  • Index is uneven (idx = range(4) solves the issue)

I found a similar question, but this is not the case for me. df.index is of class Int64Index. Is this an expected behavior or something I should report to the issue tracker?

yudai-nkt
  • 262
  • 2
  • 8
  • 1
    pandas bar plots are categorical, hence the bars are always at positions 0,1,... N-1. – ImportanceOfBeingErnest Jan 09 '20 at 14:25
  • @ImportanceOfBeingErnest That explains the problem and the xtick labels being rotated, thanks. Is it impossible to make it numerical? DataFrames in my actual case have many columns to plot as bar charts, so pandas solution/workaround is very much appreciated (I myself try to find a way as well). – yudai-nkt Jan 09 '20 at 15:15
  • Yes, use a matplotlib chart instead. `ax.bar(...)` and `ax.plot(...)` – ImportanceOfBeingErnest Jan 09 '20 at 15:26

0 Answers0