5

I have the following data set: In[55]: usdbrl Out[56]: Date Price Open High Low Change STD 0 2016-03-18 3.6128 3.6241 3.6731 3.6051 -0.31 0.069592 1 2016-03-17 3.6241 3.7410 3.7449 3.6020 -3.16 0.069041 2 2016-03-16 3.7422 3.7643 3.8533 3.7302 -0.62 0.068772 3 2016-03-15 3.7656 3.6610 3.7814 3.6528 2.83 0.071474 4 2016-03-14 3.6618 3.5813 3.6631 3.5755 2.23 0.070348 5 2016-03-11 3.5820 3.6204 3.6692 3.5716 -1.09 0.076458 6 2016-03-10 3.6215 3.6835 3.7102 3.6071 -1.72 0.062977 7 2016-03-09 3.6849 3.7543 3.7572 3.6790 -1.88 0.041329 8 2016-03-08 3.7556 3.7826 3.8037 3.7315 -0.72 0.013700 9 2016-03-07 3.7830 3.7573 3.7981 3.7338 0.63 0.000000

I want to plot Price against Date: enter image description here

But I would like to color the line by a third variable (in my case Date or Change).

Could anybody help with this please?

Thanks.

Matt Messersmith
  • 12,939
  • 6
  • 51
  • 52
Porco
  • 195
  • 1
  • 4
  • 16
  • I'm not following what you mean by coloring the line by a third variable. If you have another variable, then you need another line (maybe of a different color) or a 3D plot, right? – Matt Messersmith Apr 08 '16 at 17:26
  • Do you want the line in one color, or several? How do you choose the color? – Reblochon Masque Apr 08 '16 at 17:27
  • 1
    I read it as "I want to express a third dimension of data / third kind of information by changing color of the segments of the line". – Jiri Tousek Apr 08 '16 at 19:56

2 Answers2

11

I've wrote a simple function to map a given property into a color:

import matplotlib.cm as cm
import matplotlib.pyplot as plt

def plot_colourline(x,y,c):
    col = cm.jet((c-np.min(c))/(np.max(c)-np.min(c)))
    ax = plt.gca()
    for i in np.arange(len(x)-1):
        ax.plot([x[i],x[i+1]], [y[i],y[i+1]], c=col[i])
    im = ax.scatter(x, y, c=c, s=0, cmap=cm.jet)
    return im

This function normalizes the desired property and get a color from the jet colormap. The PathCollection returned by the function will also enable plotting a colorbar. You may want to use a different one. Then, get the current axis and plot different segments of your data with a different colour. Because I am doing a for loop, you should avoid using it for a very large data set, however, for normal purposes it is useful.

Consider the following example as a test:

import numpy as np
import matplotlib.pyplot as plt

n = 100
x = 1.*np.arange(n)
y = np.random.rand(n)
prop = x**2

fig = plt.figure(1, figsize=(5,5))
ax  = fig.add_subplot(111)
im = plot_colourline(x,y,prop)
fig.colorbar(im)

enter image description here

Rob S
  • 27
  • 1
  • 7
Alejandro
  • 3,263
  • 2
  • 22
  • 38
5

You could color the data points by a third variable, if that would help:

dates = [dt.date() for dt in pd.to_datetime(df.Date)]
plt.scatter(dates, df.Price, c=df.Change, s=100, lw=0)
plt.plot(dates, df.Price)
plt.colorbar()
plt.show()

enter image description here

screenpaver
  • 1,120
  • 8
  • 14