question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to set the color of a plotted line directly/manually?

See original GitHub issue

I have found some examples where a color scale is defined and a category variable is chosen based on which the plots are colored. E.g. here: https://github.com/altair-viz/altair/issues/921

I want the user to be able to plot various lines onto a LayerChart, and select the color manually for each line added (i.e. choose a color from a dropdown list, click plot, and add a new plot to the existing chart with the color chosen). How can I directly tell altair to plot using a certain color?

I tried:

lines = alt.Chart(df).mark_line().encode(
    x=alt.X(...),
    y=alt.Y(...),
    color='rgb(255,184,56)'
)

but this does not work. Thanks.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

5reactions
jakevdpcommented, May 3, 2019

Two ways to do this:

alt.Chart(df).mark_line(color="#FFAA00").encode(
  x='x',
  y='y'
)

or

alt.Chart(df).mark_line().encode(
  x='x',
  y='y',
  color=alt.value("#FFAA00")
)

The reason your first approach doesn’t work is because it indicates you want to encode using a column named 'rgb(255,184,56)'.

See Customizing Visualizations for more information.

0reactions
RajUnikiecommented, Jun 11, 2020

Thanks. It fit my purpose. Though I tried alt.Scale as suggested here, the color is not consistent for the plots called several times on the same page. Now it is. Probably I missed a common range/domain definition.

Here is my not so good looking code. Just in case it helps someone introduce legends to multi layer, though I don’t recommend taking this path…

       domain = ["Speed 1", "Speed 2", "x", "y"]
        range_ = ["steelblue", "lightsalmon", "green", "red"]
        selector = alt.selection_single(fields=["Legend"], empty="all", bind="legend")
        dataframe_1["Legend"] = domain[0]
        base = alt.Chart(
            title="Some title",
        ).interactive()
        dataframe_2["Legend"] = domain[1]
        sdf = alt.Chart(dataframe_2.reset_index())
        udf_chart = (
            base.mark_line(color="steelblue")
            .encode(
                x=alt.X("timestamp", axis=alt.Axis(title="Timestamp")),
                y=alt.Y("speed", axis=alt.Axis(title="Speed in m/s")),
                color=alt.Color("Legend", scale=alt.Scale(domain=domain, range=range_)),
                opacity=alt.condition(selector, alt.value(1), alt.value(0)),
            )
            .add_selection(selector)
            .properties(width=2000)
        )
        sdf_chart = sdf.mark_line(color="lightsalmon").encode(
            x="timestamp",
            y="speed",
            color=alt.Color("Legend", scale=alt.Scale(domain=domain, range=range_)),
            opacity=alt.condition(selector, alt.value(1), alt.value(0)),
        )

        if x1.empty:
            x_lines = text_hb = None
        else:
            x1.loc[x1.index, "Legend"] = "xline"
            x_lines = (
                alt.Chart(x1.reset_index())
                .mark_rule(color="chartreuse", strokeWidth=1)
                .encode(x="timestamp")
            )
            text_x1 = x_lines.mark_text(align="left", baseline="top", y=ymax).encode(
                text="Legend"
            )

        if y1.empty:
            y_lines = text_ra = None
        else:
            y1.loc[y1.index, "Legend"] = "yline"
            y_lines = (
                alt.Chart(y1.reset_index())
                .mark_rule(color="lightpink", strokeWidth=2)
                .encode(x="timestamp")
            )
            text_y1 = y_lines.mark_text(align="left", baseline="top", y=ymax).encode(
                text="Legend"
            )

        if x.empty:
            x_dot = None
        else:
            x["Legend"] = domain[2]
            x_dot = (
                alt.Chart(x)
                .mark_circle(color="green", size=150)
                .encode(
                    x="timestamp",
                    y="speed",
                    color=alt.Color(
                        "Legend", scale=alt.Scale(domain=domain, range=range_)
                    ),
                )
            )

        if y.empty:
            y_dot = None
        else:
            y["Legend"] = domain[3]
            y_dot = (
                alt.Chart(y)
                .mark_circle(color="red", size=150)
                .encode(
                    x="timestamp",
                    y="speed",
                    color=alt.Color(
                        "Legend", scale=alt.Scale(domain=domain, range=range_)
                    ),
                )
            )

        chart_list = [
            "x_lines",
            "y_lines",
            "text_x1",
            "text_y1",
            "x_dot",
            "y_dot",
        ]
        to_plot = "udf_chart + sdf_chart"
        for item in chart_list:
            if eval(item) is not None:
                to_plot = to_plot + " + " + item
        st.altair_chart(eval(to_plot))

(Of course, I would like to avoid ‘eval’ … work in progress)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Control How Plotting Functions Select Colors and Line Styles
You can change the colors, line styles, and markers of plot objects by modifying the ColorOrder or LineStyleOrder properties of the axes, or...
Read more >
How to change the plot line color from blue to black?
The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done...
Read more >
matplotlib.pyplot.plot — Matplotlib 2.1.2 documentation
Line styles and colors are combined in a single format string, as in 'bo' for blue circles. The kwargs can be used to...
Read more >
How to change Colors in ggplot2 Line Plot in R - GeeksforGeeks
It utilizes points and lines to represent change over time. Line graphs are drawn by plotting different points on their X coordinates and...
Read more >
How to Change Plot Line Styles and Colors in MATLAB
... details about customization of Plots in terms of Styles and Colors in MATLAB.Contents of the Video:1. Plots in MATLAB2. Change Line S......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found