layover plots in one figure in Python

Viewed 112

I can layover two curves in 1 plot like so

X = np.array([1, 5, 8])
y = np.array([2, 10, 3])

x_max = np.array([5])
y_max = np.array([10])

fig, ax = plt.subplots(figsize=(8,6));

ax.plot(X, y, 'k--', label="savitzky")
ax.scatter(x_max, y_max, s=200, c='k', marker='*');

Then I will get the following:

enter image description here

Lets say I have a data frame and I want to plot all of its columns at once. I can do that like so:

df_2 = pd.DataFrame(data = {'col_1':np.array([2, 10, 3]), 'col_2':np.array([3, 4, 7])}, 
                index = np.array([1, 5, 8]))
df_2.plot()

to get:

enter image description here

My question is how can I combine these two so I can plot the whole dataframe at once and then lay over my vectors of maximum points?(my real data frame is bigger than this, and so are the vectors of maximums)

Thanks

2 Answers

The following is one way to do it:

  1. Create an axis object ax
  2. Plot the DataFrame on this axis
  3. Get the maximum element and the corresponding index for each column
  4. Make a scatter plot on the same axis ax

fig, ax = plt.subplots()

df_2 = pd.DataFrame(data = {'col_1':np.array([2, 10, 3]), 
                            'col_2':np.array([3, 4, 7])}, 
                            index = np.array([1, 5, 8]))
df_2.plot(ax=ax) # Plot the DataFrame on ax object

max_points = [(df_2[col].idxmax(),  df_2[col].max()) for col in df_2.columns]

ax.plot(*zip(*max_points), 'b*', ms=10) # Unpack the list of (x, y) tuples
ax.set_xlim(None, 8.2)

enter image description here

You can do it like this:

Here I have assigned the axis object given by the df_2.plot to ax and plotted the further graph on it (ax) X = np.array([1, 5, 8]) y = np.array([2, 10, 3])

x_max = np.array([5])
y_max = np.array([10])

df_2 = pd.DataFrame(data = {'col_1':np.array([2, 10, 3]), 'col_2':np.array([3, 4, 7])}, index = np.array([1, 5, 8]))
ax=df_2.plot(figsize=(8,6))

ax.plot(X, y, 'k--', label="savitzky")
ax.scatter(x_max, y_max, s=200, c='k', marker='*');

plt.show()

<code>Output</code>

Related