1

I want to plot two dataframes in one 3D scatterplot.

This is the code I have for one dataframe:

import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D

...

sns.set(style = "darkgrid")

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
x = df['xitem']
y = df['yitem']
z = df['zitem']

ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_zlabel("Z Label")

ax.scatter(x, y, z)

plt.show()

I can't figure out how to adjust this so I have two different dataframes plotted on the same plot but with different colors. How can I do this?

Edit: I'm looking for how to use two dataframes for a 3D plot specifically.

0

1 Answer 1

1

Assuming that you have two DataFrame called df1 and df2, both containing columns 'xitem', 'yitem', 'zitem', you can plot them in this way:

for curr_df, c in zip((df1, df2), ('b', 'r')):
    ax.scatter(*curr_df[['xitem', 'yitem', 'zitem']].values.T, color=c)

Here a complete example:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

sns.set(style = "darkgrid")

df1 = pd.DataFrame(
    data=np.random.random((100, 3)) + np.array([1, 1, 1]),
    columns=['xitem', 'yitem', 'zitem'],
)

df2 = pd.DataFrame(
    data=np.random.random((100, 3)),
    columns=['xitem', 'yitem', 'zitem'],
)

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

for curr_df, c in zip((df1, df2), ('b', 'r')):
    ax.scatter(*curr_df[['xitem', 'yitem', 'zitem']].values.T, color=c)

ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_zlabel("Z Label")

plt.show()

enter image description here

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

2 Comments

@Mr. T thanks, I didn't know that. I've updated the answer

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.