issue with custom plots in taipy

57 Views Asked by At

I see its possible to add a custom plot in Taipy.

import plotly.graph_objects as go import numpy as np

# Function to create rotation matrix
def create_rotation_matrix(A, B, C):
    Rz = np.array([[np.cos(A), -np.sin(A), 0], [np.sin(A), np.cos(A), 0], [0, 0, 1]])
    Ry = np.array([[np.cos(B), 0, np.sin(B)], [0, 1, 0], [-np.sin(B), 0, np.cos(B)]])
    Rx = np.array([[1, 0, 0], [0, np.cos(C), -np.sin(C)], [0, np.sin(C), np.cos(C)]])
    return Rz @ Ry @ Rx

# Data points
BASE_DATA = {
    1: {"X": 205.204498, "Y": -1396.70898, "Z": 383.235413, "A": -87.5785, "B": 0.539600, "C": -13.9059},
    2: {"X": 298.000, "Y": -1475.49597, "Z": 335.000, "A": -88.8150, "B": 0.130000, "C": -0.178000}
}

# Axis length for orientation lines
axis_length = 100

# Plotly figure
fig = go.Figure()

for key, point in BASE_DATA.items():
    # Convert angles from degrees to radians
    A, B, C = np.radians(point["A"]), np.radians(point["B"]), np.radians(point["C"])

    # Creating rotation matrix for A, B, C
    R = create_rotation_matrix(A, B, C)

    # Orientation vectors for the reference frame
    ref_frame_vectors = R @ np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).T

    # Adding the point
    fig.add_trace(go.Scatter3d(x=[point["X"]], y=[point["Y"]], z=[point["Z"]],
                               mode='markers', marker=dict(size=4, color=['blue', 'orange'][key-1])))

    # Adding orientation vectors for the reference frame as lines
    for i, color in zip(range(3), ['red', 'green', 'blue']):
        fig.add_trace(go.Scatter3d(x=[point["X"], point["X"] + axis_length * ref_frame_vectors[i, 0]], 
                                   y=[point["Y"], point["Y"] + axis_length * ref_frame_vectors[i, 1]], 
                                   z=[point["Z"], point["Z"] + axis_length * ref_frame_vectors[i, 2]], 
                                   mode='lines', line=dict(color=color, width=2)))

# Optionally, connecting the two points
fig.add_trace(go.Scatter3d(x=[BASE_DATA[1]["X"], BASE_DATA[2]["X"]],
                           y=[BASE_DATA[1]["Y"], BASE_DATA[2]["Y"]],
                           z=[BASE_DATA[1]["Z"], BASE_DATA[2]["Z"]],
                           mode='lines', line=dict(color='grey', width=2, dash='dash')))

# Layout settings
fig.update_layout(scene=dict(
                    xaxis_title='X Axis',
                    yaxis_title='Y Axis',
                    zaxis_title='Z Axis'),
                  margin=dict(r=0, b=0, l=0, t=0))

# Show plot
fig.show()

# Function to convert Plotly figure to HTML
def expose_plotly(fig):
    buffer = io.StringIO()
    fig.write_html(buffer)
    return buffer.getvalue()

# Taipy GUI setup

def on_user_content(state, path: str, query: dict):
    return expose_plotly(fig)  # Use the fig object you created

def on_init(state):
    state.uc_url = get_user_content_url(state, "hello", {"t": "a"})

I tried adding this to existing page like this and markdown code as : <|part|page={uc_url}|height=800px|>

this isn't quiet working for me. Also, how can I update the plot on the go when I change values?

1

There are 1 best solutions below

2
Florian Jacta On

What does not work here? Yes, you can change the fig on the fly. You just have to create a callback that will regenerate the URL:

state.uc_url = get_user_content_url(state, "hello", {"t": "a"})

And the function creating your fig can also use the state parameter to get the values from the user interface:

def create_fig(state):
   fig = ... # use the state to get the values from you user interface
   return fig


def on_user_content(state, path: str, query: dict):
    return expose_plotly(create_fig(state))  # Use the fig object you created

Also, it is possible in the develop version of Taipy to directly put a Plotly graph in Taipy.

...
# your code to create your fig

md = "<|chart|figure={fig}|>"

Gui(md).run()

For example:

from taipy.gui import Gui 
import plotly.express as px

# Bubble figure
df = px.data.gapminder()

bubble_fig = px.scatter(df.query("year==2007"), x="gdpPercap", y="lifeExp",
             size="pop", color="continent",
                 hover_name="country", log_x=True, size_max=60)

# Choropleth figure
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)

import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
                   dtype={"fips": str})

import plotly.express as px

choropleth_fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
                           color_continuous_scale="Viridis",
                           range_color=(0, 12),
                           scope="usa",
                           labels={'unemp':'unemployment rate'}
                          )
choropleth_fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})

# Displaying the figures

md = """
<|chart|figure={bubble_fig}|>

<|chart|figure={choropleth_fig}|>
"""

Gui(md).run()

Figure with Plotly

This will be out with Taipy 3.1 in a month. To have the develop branch and this feature now, you need git installed in your Python environment and node.js on your computer. Then:

pip install taipy==3.1.0.dev0