I haven't really attempted any way to do this, but I am wondering if there is a way to merge two plots that already exist into one graph. Any input would be greatly appreciated!
Asked
Active
Viewed 2.6k times
13
-
What plotting library are you using? What type of plots? Please provide more details. – Gareth Oct 03 '12 at 14:08
-
@Gareth The library would most likely be matplotlib, and the two graphs in question each have regular line plots, as well as histograms. They look similar, and have the same axes, though they have separate date ranges on the x-axis. – user1620716 Oct 03 '12 at 14:11
-
Do you want to merge the _data_ of two already existing plots? Say a line plot in red and another in blue - as an example you would like to see a new plot in green of the two datasets? (We are assuming for some strange reason you don't have access to the original data correct?) – Hooked Oct 03 '12 at 14:16
-
Something like that may be ideal. We can assume that there is no access to the original data. – user1620716 Oct 03 '12 at 14:20
2 Answers
9
Here is a complete minimal working example that goes through all the steps you need to extract and combine the data from multiple plots.
import numpy as np
import pylab as plt
# Create some test data
secret_data_X1 = np.linspace(0,1,100)
secret_data_Y1 = secret_data_X1**2
secret_data_X2 = np.linspace(1,2,100)
secret_data_Y2 = secret_data_X2**2
# Show the secret data
plt.subplot(2,1,1)
plt.plot(secret_data_X1,secret_data_Y1,'r')
plt.plot(secret_data_X2,secret_data_Y2,'b')
# Loop through the plots created and find the x,y values
X,Y = [], []
for lines in plt.gca().get_lines():
for x,y in lines.get_xydata():
X.append(x)
Y.append(y)
# If you are doing a line plot, we don't know if the x values are
# sequential, we sort based off the x-values
idx = np.argsort(X)
X = np.array(X)[idx]
Y = np.array(Y)[idx]
plt.subplot(2,1,2)
plt.plot(X,Y,'g')
plt.show()

Hooked
- 84,485
- 43
- 192
- 261
-
This is almost exactly what I'm looking for! I'm going to give it a try. – user1620716 Oct 03 '12 at 15:22
1
Assuming you are using Matplotlib, you can get the data for a figure as an NX2 numpy array like so:
gca().get_lines()[n].get_xydata()

Gareth
- 3,502
- 4
- 20
- 21