1

I've tested matlpotlib using CSV file, which y and z value isn't connected as below.

I can visualize this data using a scatter plot but I can't connect these dots but the final goal is creating a connected graph using the line plot. Why it can't visualize with the line plot?

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv(r'C:\Users\PythonTest\source\file.csv')
ax1 = plt.subplot2grid((1, 1), (0, 0))
x = df.time
y = df.gx
z = df.sp
# ax1.scatter(x, y, color='k', s=0.1)
# ax1.scatter(x, z, color='c', s=0.1)
ax1.plot(x, y, color='k')
ax1.plot(x, z, color='c')
plt.show()
0

1 Answer 1

2

You can scatter plot discontinuous values, but you cannot plot a line of discontinuous values because matplotlib cannot magically know what values you want in between specified values. Do you want to treat missing values as 0? As the previous value? Something else?

One way to accomplish what I think you probably want is to drop the missing values. Let's do time and gx:

time_gx = df.drop(columns=['sp']).dropna()
plt.plot(time_gx['time'], time_gx['gx'])
plt.xlabel('time')
plt.ylabel('gx')
plt.show()

enter image description here

If instead you want to treat missing values as the last specified value, just use ffill:

df2 = df.ffill()
plt.plot(df2['time'], df2['gx'])
plt.xlabel('time')
plt.ylabel('gx')
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I didn't get your meaning. I want to treat null values as previous value, and it's hard to understand why there is sp in time_gx = df.drop(columns=['sp']).dropna()? If there are 10 columns, should I have to drop 9 columns? And I've used ax1 because I want to visualize 2 graphs in a canvas. In this case, how to use what you told me?
@Gyeyoon.Lee df.drop() wants to know which columns you don't want, which is why I have it 'sp': in dropping null values that are inconsistent across columns, you will have to drop all other columns (if you have a lot of columns, just do the complementary operation, filter, in which you specify the columns you want to keep instead of drop). This step is not needed for forward fill, though (I added a forward fill example). You can keep using separate subplots, that isn't relevant to your original issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.