2

I was wondering how one would create a 3D scatter chart in Taipy. I tried this code initially:

import pandas as pd
import numpy as np
from taipy import Gui

df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=list('xyz'))
df['cluster1']=np.random.randint(0,3,100)
my_page ="""
Creation of a 3-D chart:

<|{df}|chart|type=Scatter3D|x=x|y=y|z=z|mode=markers|color=cluster|>
"""
Gui(page=my_page).run()

This does indeed display a 3D plot, but the colors (clusters) do not show up. Any hint?

st_killer
  • 31
  • 5
  • Hey st_killer, Feel free to join our Discord Server discord.com/invite/SNNsCDj9? and connect with like-minded individuals and collaborate on your web application buildings :) – Rym Guerbi Michaut Jul 17 '23 at 09:52

2 Answers2

4

Yes, you need some massaging of your dataframes to do it. Here's a sample code that achieves this:

import pandas as pd
import numpy as np
from taipy import Gui

df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=list('xyz'))
df['cluster1']=np.random.randint(0,3,100)

# Create a list of 3 dataframes, one per cluster
datas = [df[df['cluster1']==i] for i in range(3)]

properties = {
}
# create dynamically the property list.
# str(i) points to a dataframe index
# "/x" points to the column value in the selected dataframe
for i in range(len(datas)):
    properties[f"x[{i+1}]"] = str(i)+"/x"
    properties[f"y[{i+1}]"] = str(i)+"/y"
    properties[f"z[{i+1}]"] = str(i)+"/z"
    properties[f'name[{i+1}]'] = str(i+1)

print(properties)

chart = "<|{datas}|chart|type=Scatter3D|properties={properties}|mode=markers|height=800px|>"
Gui(page=chart).run()
1

In fact, with the new release: Taipy 1.1, this is very easy to do in a few lines of code:

import pandas as pd
import numpy as np
from taipy import Gui

color_map={0:"blue",1:'green', 2:"red"}
df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=list('xyz'))
df['cluster1'] = np.random.randint(0,3,100)

df['cluster_colors'] = df.apply(lambda row: color_map[row.cluster1], axis=1)

marker = {"color":"cluster_colors"}
chart = "<|{df}|chart|type=Scatter3D|x=x|y=y|z=z|marker={marker}|mode=markers|height=800px|>"
Gui(page=chart).run()

If you want to leave it to Taipy to pick the colors for you, then you can simply use:

import pandas as pd
import numpy as np
from taipy import Gui

df = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=list('xyz'))
df['cluster1'] = np.random.randint(0,3,100)

marker = {"color":"cluster1"}
chart = "<|{df}|chart|type=Scatter3D|x=x|y=y|z=z|marker={marker}|mode=markers|height=800px|>"
Gui(page=chart).run()
st_killer
  • 31
  • 5