2

I want to superpose two graphs where x-axis corresponds. The first is on the full range, while second is upon a sub-interval.

test1 = pd.DataFrame(
    {
        'x': [1,2,3,4,5,6,7,8,9],
        'y': [0,1,1,2,1,2,1,1,1]
    }
)

test2 = pd.DataFrame(
    {
        'x': [1,2,4,5,8],
        'y': [3,2,2,3,3]
    }
)
  • What kind of graph do you need? Does your plot need to show two different functions or one only? – lemon Jan 25 '23 at 17:38
  • I want two different functions on the same graph. ```plt.plot(test1["x"], test1["y"]) plt.plot(test2["x"], test2["y"])``` for bigger data, the skipped values cause scaling issue – bugrahaskan Jan 25 '23 at 17:42
  • 1
    The correct way is to plot the dataframes directly `ax = test1.plot(x='x', y='y', label='test1')` and `test2.plot(x='x', y='y', ax=ax, label='test2')` – Trenton McKinney Jan 26 '23 at 01:27

2 Answers2

2

You can use the xlim() function in library.

Example:

import matplotlib.pyplot as plt
import pandas as pd

test1 = pd.DataFrame(
    {
        'x': [1,2,3,4,5,6,7,8,9],
        'y': [0,1,1,2,1,2,1,1,1]
    }
)

test2 = pd.DataFrame(
    {
        'x': [1,2,4,5,8],
        'y': [3,2,2,3,3]
    }
)

plt.plot(test1['x'], test1['y'], 'b-', label='test1')
plt.plot(test2['x'], test2['y'], 'r-', label='test2')
plt.xlim(min(test1['x']), max(test1['x']))
plt.legend()
plt.show()

Result:


img

Mario
  • 1,631
  • 2
  • 21
  • 51
1

IIUC, you can add to the "y" values in the first one the "y" values colliding in the second where collision is over "x" values:

plt.plot(test1["x"], test1["y"].add(test1["x"].map(test1.set_index("x")["y"])))

to get

enter image description here

Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38