Home > database >  How to prevent spans from hiding bar charts?
How to prevent spans from hiding bar charts?

Time:09-02

I'm plotting a bar graphic and horizontal spans with this code:

fig = plt.figure('Graphic', figsize=(20,15), dpi=400)
     
ax1 = fig.add_axes([0.1, 0.1, 0.85, 0.75])
data.plot('DATE',["PP"],kind='bar',color='black', fontsize = 15.0,ax=ax1,alpha=1)
data.plot('DATE',['PP'],kind='line',marker='*',style=['--'],linewidth=1,color='gray', ms=5,ax=ax1)

ax1.axhspan(0, 1, facecolor='lightyellow', alpha=1)
ax1.axhspan(1, 1.5, facecolor='yellow', alpha=1)
ax1.axhspan(1.5, 2, facecolor='lime', alpha=1)
ax1.axhspan(2, 3.5, facecolor='green', alpha=1)
ax1.axhspan(0, -1, facecolor='bisque', alpha=1)
ax1.axhspan(-1, -1.5, facecolor='orange', alpha=1)
ax1.axhspan(-1.5, -2, facecolor='pink', alpha=1)
ax1.axhspan(-2, -3.5, facecolor='red', alpha=1)

The issue is that spans are hiding the Bar graphic. I would like to be able to visualize the spans with the bar graphs. Both with alpha=1. I don't want to reduce the alpha values.

Is this possible?

Thanks in advance.

I am displaying the image with axhspans with alpha=1 covering the bar charts.

enter image description here

CodePudding user response:

The order of display in the pandas plot is not adjustable, so I guess we have to deal with it in matplotlib. ax is set up with a line chart and horizontal fill, and a bar chart is added as a second axis. Then I get the order of the line chart, add 1 to the value of the line chart, and set the display order to the bar chart. Since no data was provided, stock price data was used as a sample.

import yfinance as yf
import pandas as pd
data = yf.download("AAPL", start="2022-06-01", end="2022-09-01")
data.index = pd.to_datetime(data.index)

import matplotlib.pyplot as plt

fig = plt.figure('Graphic', figsize=(10,7.5), dpi=100)
     
ax1 = fig.add_axes([0.1, 0.1, 0.85, 0.75])
ax1.plot(data.index, data['Close'], marker='*', linestyle='--', linewidth=1, color='gray', ms=5)

ax1.axhspan(170, 180, facecolor='lightyellow', alpha=1)
ax1.axhspan(160, 170, facecolor='yellow', alpha=1)
ax1.axhspan(150, 160, facecolor='lime', alpha=1)
ax1.axhspan(145, 150, facecolor='green', alpha=1)
ax1.axhspan(140, 145, facecolor='bisque', alpha=1)
ax1.axhspan(135, 140, facecolor='orange', alpha=1)
ax1.axhspan(130, 135, facecolor='pink', alpha=1)
ax1.axhspan(120, 130, facecolor='red', alpha=1)

ax2 = ax1.twinx()
ax2.bar(x=data.index, height=data['Volume'], color='black')
ax2.set_zorder(ax1.get_zorder() 1)
ax2.set_frame_on(False)

ax1.set_ylim(120, 180)
plt.show()

enter image description here

CodePudding user response:

I noticed two things that needed to change.

  1. When you use pandas line and bar plots with X-axis being dates, there was/is a bug. Refer to this enter image description here

  • Related