0

My code looks like this:

price = np.array(df.price) low_price = np.array(df['mid price'])

price is equal to: [nan,nan, 2, 3, nan,nan, 1]

low_price is equla to : [1, 2, 2, 3, 3, 4, 1]

When I plot them:

plt.plot(low_price, 'k', linewidth=2)
plt.plot(price, 'y', linewidth=2)

They are plotted on the same line with different colors, but how can I change the X axis as well? I have no clue.. thanks!

This is more or less related to that question: Matplotlib: Changing the color of an axis

But I would like to change the color only for specific data points.

Viktor.w
  • 1,787
  • 2
  • 20
  • 46

1 Answers1

2

One (not so great) hack could be to draw a line ontop of the part of the axes by turning off it's clip:

import numpy as np
import matplotlib.pyplot as plt

price = [np.nan, np.nan, 2, 3, np.nan, np.nan, 1]
low_price = [1, 2, 2, 3, 3, 4, 1]

plt.plot(low_price, "k", lw=2)
plt.plot(price, "y", lw=2)

# plot line on axes
line = plt.plot([2, 3], [0, 0], "y", lw=2)[0]
line.set_clip_on(False)  # turn off clip
plt.ylim(0, 4)  # set ylim so axes doesn't move
plt.show()

enter image description here

Alex
  • 795
  • 1
  • 7
  • 11
  • Hi @alex, what does the `line.set_clip_on(False) ` , and also I do not get the `plt.ylim(0, 4) ` line of code, thanks! – Viktor.w Apr 24 '19 at 09:21
  • Hey @Viktor.w! `plt.ylim(0, 4)` fixes the y-axis extent from 0 to 4. Matplotlib automatically extends the axis if you plot something at the edge of the canvas (e.g. on the axis) - so you need to fix the axis in place if you want to draw on top of it (in this case at 0, but could be anything). Now normally matplotlib hides (clips) anything plotted outside the canvas - but you can disable that for specific elements. As the horizontal yellow line plots directly at the border of the canvas (on the axis), it wouldn't be rendered if we wouldn't turn off clipping for it using `set_clip_on(False)`. – Alex Apr 24 '19 at 09:42