Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: fails to plot 2 plots with secondary y axis when index type is PeriodIndex and plot kinds are different #61161

Open
2 of 3 tasks
Ev2geny opened this issue Mar 21, 2025 · 3 comments · May be fixed by #61173
Open
2 of 3 tasks
Labels

Comments

@Ev2geny
Copy link

Ev2geny commented Mar 21, 2025

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd
import matplotlib.pyplot as plt

print(pd.__version__)

index = pd.period_range('2023', periods=3, freq='Y')
df = pd.DataFrame({
    'col1': [10, 20, 30],
    'col2': [40, 25, 10]
}, index=index)

# Workaround !!!!
# df.index = df.index.astype(str)

print(type(df.index))

fig, ax = plt.subplots()

df['col1'].plot(kind='bar', ax=ax)

ax2 = ax.twinx()

df['col2'].plot(kind='line', ax=ax2, color = 'r')

plt.show()

Issue Description

I seem to have found the following bug:

It is not possible to plot 2 plots with different Y axis when the following 2 conditions are met:

  • plot kinds are different (e.g. 'bar' and 'line')
  • index type is PeriodIndex

Image

The easy workaround is to convert index to string:

Image

If the parameter 'kind' of both axis is identical, then it works as well without workound

Image

Expected Behavior

Both plots shall be possible to be seen

Installed Versions

INSTALLED VERSIONS

commit : 0691c5c
python : 3.12.7
python-bits : 64
OS : Windows
OS-release : 11
Version : 10.0.22631
machine : AMD64
processor : Intel64 Family 6 Model 170 Stepping 4, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_Netherlands.1252

pandas : 2.2.3
numpy : 2.2.1
pytz : 2024.2
dateutil : 2.9.0.post0
pip : 24.2
Cython : None
sphinx : None
IPython : 8.31.0
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : 4.12.3
blosc : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : 2024.10.0
html5lib : 1.1
hypothesis : None
gcsfs : None
jinja2 : 3.1.4
lxml.etree : 5.3.0
matplotlib : 3.10.0
numba : None
numexpr : None
odfpy : None
openpyxl : 3.1.5
pandas_gbq : None
psycopg2 : None
pymysql : None
pyarrow : None
pyreadstat : None
pytest : 8.3.3
python-calamine : None
pyxlsb : 1.0.10
s3fs : None
scipy : 1.14.1
sqlalchemy : None
tables : None
tabulate : 0.9.0
xarray : None
xlrd : None
xlsxwriter : None
zstandard : None
tzdata : 2024.2
qtpy : None
pyqt5 : None

@Ev2geny Ev2geny added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Mar 21, 2025
@Ev2geny Ev2geny changed the title BUG: fails to plot 2 plots with secondary y axis when index type is PeriodIndex and plot knds are different BUG: fails to plot 2 plots with secondary y axis when index type is PeriodIndex and plot kinds are different Mar 21, 2025
@snitish
Copy link
Member

snitish commented Mar 21, 2025

Might be a duplicate of #61005

@rhshadrach rhshadrach added Visualization plotting and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Mar 22, 2025
@rhshadrach
Copy link
Member

Agreed @snitish - but I'm thinking we leave both open to confirm. It seems like it might be possible to fix one without the other.

@MartinBraquet MartinBraquet linked a pull request Mar 24, 2025 that will close this issue
5 tasks
@MartinBraquet
Copy link
Contributor

MartinBraquet commented Mar 24, 2025

The crux of the issue lies in the value of the numeric xticks (aka position of the xticks, or tick_pos in the code). The tick positions always start at 0 in the bar class

self.tick_pos = np.arange(len(data))

while the tick positions in the line class are computed by a PeriodConverter used in matplotlib here.

Since the xticks in the example above are not numeric (of type pandas.Period), matplotlib assigns the tick positions by itself: 0 maps onto 1970, so 2023-2025 map onto around 53-55. So the bar spans 0-2 and the line spans 53-55, i.e., they don't overlap the same x range. Then, the pandas plotting routine restricts the x range to the last plot range, which essentially crops out the first plot.

The current pandas plotting routine coincidentally works for string indices as, in such cases, matplotlib / the converter assigns tick positions starting at 0, as in BarPlot.

I believe the most straightforward way to fix the issue is to change the tick positions in BarPlot to reflect how it's computed in PeriodConverter, as attempted in #61173 .

Please let me know if the approach sounds reasonable.

Note that the same issue appears in the BoxPlot class, and possibly other ones, so there will change needed in that class in order to see line and box plots on the same plot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants