0

I've recently gotten into plotly and am absolutely loving it, so am trying to use it in each project I do.

With matplotlib I can plot a line plot and a scatter plot on the same graph using the code below.

plt.figure(figsize = (20,5))
plt.scatter(x, y)
plt.plot(x, y_pred, color = "r")
plt.show()

Using the trendline parameter in the scatter function inside plotly.express I can plot a line of best fit through the scattered points, but I don't want that as I am trying to demonstrate how to calculate that line.

Thanks for the help in advance!

3 Answers 3

1

Using same defined arrays / lists, x, y, y_pred. An equivalent approach is to use Plotly Express to create a figure then add additional traces to it.

import pandas as pd
import numpy as np
import plotly.express as px

x = np.linspace(1, 20, 16)
y = np.random.uniform(1, 6, 16)
y_pred = y * 1.1

fig = px.scatter(x=x, y=y, color_discrete_sequence=["yellow"])
fig.add_traces(px.line(x=x, y=y_pred, color_discrete_sequence=["red"]).data)

enter image description here

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

4 Comments

Thanks man! Just one more quick question. Like we can change the color of the plotted graph in matplotlib using the color attribute, is there any way to change the graph's color in plotly?.
that's done in code sample with update_traces(line_color="red")
I meant that can we change the color of the plot plotted using px.scatter(x=x, y=y)? I passed line_color = "red" inside the scatter function and it threw an error.
updated answer if you want to do directly within Plotly Express call.
0

You can use fig.add_shape after you have created the scatter plot like so:

fig.add_shape(
    type="line",
    x0=0,
    y0=0,
    x1=10,
    y1=10,
    line=dict(width=1, dash="dash"),
)

Comments

0

If you create a line plot instead, you can actually use the markers arument:

px.line(x=x, y=y, markers=True)

https://i.sstatic.net/aJaaM.png

https://plotly.com/python-api-reference/generated/plotly.express.line.html

Comments

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.