0

I have a dataframe such as below and I am trying to use the example plot code (given below) to generate a similar style line series plot for my dataframe.

df = pd.DataFrame({'x': np.linspace(0, 10, 100),
                       'run0_Y': np.sin(np.linspace(0, 10, 100)),
                       'run1_Y': np.cos(np.linspace(0, 10, 100)),
                       'run2_Y': np.cos(np.linspace(0, 10, 100)),
                       'run3_Y': np.arctan(np.linspace(0, 10, 100))
                       })
  1. I would like to generate a plot like below (see code) but I want to replace the colorbar with my dataframe headings ['run0_Y' ... 'run3_Y'] as legends for each color.
  2. 'run0_Y' and 'run1_Y' belongs to the same color but differentiated with solid line '-k' and dashed line '--k'
  3. I am stuck as to how to plot the line series from my dataframe and associate each dataframe column to its column header in the colorbar as legend.

Example plotting code:

import numpy as np
import matplotlib.pyplot as plt

# Use the spectral colormap for examples
cmap = plt.cm.Spectral

# Generate some fake data
N = 100
nlines = 10
x = np.linspace(-np.pi, np.pi, N) 
print('x: \n', x)
y = np.linspace(-np.pi, np.pi, nlines)
print('y: \n', y)

# Use np.newaxis to create [N,1] and [1,Nlines] x and y arrays
# Then broadcasting to generate Z with shape [N,Nlines]
z = np.sin(x[:,np.newaxis] + y[np.newaxis,:]/4)
print('z \n', z)

# Use 0-1 values to generate the colors with the linspace method
line_colors = cmap(np.linspace(0,1,nlines))

# We have to generate our own axis to put the colorbar in
# otherwise it "steals" space from the current axis.  Please
# let me know if anyone has found another way around this,
# because the custom axes generation is the only way I've
# figured out.
from matplotlib.gridspec import GridSpec


# fig = plt.figure(figsize = (12,6))
# nrows = 2
# gs = GridSpec(nrows,2,width_ratios=[50,1])
# ax = [plt.subplot(gs[i,0]) for i in range(nrows)]
# cbax1 = plt.subplot(gs[1,1])

# # First, plot lines w/ legend
# a = ax[0]
# a.set_title('Labeling with a legend')

# for i in range(nlines):
#     a.plot(x, z[:,i], c=line_colors[i],lw=3,label='{:4.1f}'.format(y[i]))
# leg = a.legend(loc='center left', bbox_to_anchor=(1, 0.5), ncol=2)
# leg.set_title('Y')

# # Next, plot with colorbar
# a = ax[1]
# a.set_title('Labeling with a "continuous" colorbar')

# for i in range(nlines):
#     a.plot(x, z[:,i], c=line_colors[i],lw=3,label='{:3.1f}'.format(y[i]))

# # Generate fake ScalarMappable for colorbar
# sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=y[0],vmax=y[-1]))
# sm.set_array([])  # You have to set a dummy-array for this to work...
# cbar = plt.colorbar(sm, cax=cbax1)
# cbar.set_label('Y')
# cbar.set_ticks(y)
# cbar.set_ticklabels(['{:4.1f}'.format(yi) for yi in y]) # Make 'em nicer-looking

# # Moves colorbar closer to main axis by adjusting width-spacing between subplot axes.
# fig.subplots_adjust(wspace=0.05, hspace=0.4)

# # Set axis limits
# for a in ax:
#     a.set_xlim(-np.pi, np.pi)


fig = plt.figure(figsize = (12,6))
nrows = 1
gs = GridSpec(nrows,2,width_ratios=[50,1])
ax = [plt.subplot(gs[i,0]) for i in range(nrows)]
cbax = [plt.subplot(gs[i,1]) for i in range(nrows)]

# We'll use the same fake ScalarMappable and colormap for each example
from matplotlib.colors import  ListedColormap
cmap2 = ListedColormap(line_colors) 
sm = plt.cm.ScalarMappable(cmap=cmap2,
                           norm=plt.Normalize(vmin=y[0],vmax=y[-1]))
sm.set_array([])

# # Discrete colorbar with default spacing
# a = ax[0]
# a.set_title('Labeling with a discrete colorbar')

# for i in range(nlines):
#     a.plot(x, z[:,i], c=line_colors[i],lw=2,label='{:4.1}'.format(y[i]))

# cbar = plt.colorbar(sm, cax=cbax[0])
# cbar.set_label('Y')
# cbar.set_ticks(y)
# cbar.set_ticklabels(['{:4.1f}'.format(yi) for yi in y]) # Make 'em nicer-looking

# Discrete colorbar with centered ticks
# a = ax[1]
a = ax[0]
a.set_title('Labeling with a discrete colorbar & centered labels')

for i in range(nlines):
    a.plot(x, z[:,i], c=line_colors[i],lw=2,label='{:4.1}'.format(y[i]))

# Generate custom bounds so that ticks are centered
dy = y[1]-y[0]
ybounds = np.linspace(y[0]-dy/2., y[-1]+dy/2., nlines+1)
cbar = plt.colorbar(sm, cax=cbax[0], boundaries=ybounds)
cbar.set_label('Y')
cbar.set_ticks(y)
cbar.set_ticklabels(['{:4.1f}'.format(yi) for yi in y]) # Make 'em nicer-looking

# Set axis limits
for a in ax:
    a.set_xlim(-np.pi, np.pi)

# Moves colorbar closer to main axis by adjusting width-spacing between subplot axes.
fig.subplots_adjust(wspace=0.05, hspace=0.4)

plt.show()

ex

source: https://pyhogs.github.io/colormap-examples.html

John Honai
  • 41
  • 7

0 Answers0