Home > OS >  How to plot multiple sets of X and Y in matplotlib
How to plot multiple sets of X and Y in matplotlib

Time:09-30

I want to make a plot where val1 is the X axis and val2 the Y axis. I want the plot to have both the X, Y values for model type a and b, that is, a line plot with two lines, one for each model type.

I tried this:

import pandas as pd
# df contains the dataframe above
df = df.pivot(index="alpha", columns='model', values=['val1', "val2"])

df.plot(
    figsize=(15, 13),
    xlabel = "val1",
    ylabel = "val2"
)

But that gives me a line plot for every model type for val1 and val2. That is, instead of having 2 curves that have one (val1, val2) pair for every alpha, I have 4 curves, with pairs (alpha, val_n), where n = 1:2.

How can I plot val1 against val2 by model on the same plot? No loops, please.

Extra: I've seen enter image description here

Figure-Level Plot

  • enter image description here

    CodePudding user response:

    You can convert model column to int type, and then pass as c argument in the plot function:

    df.assign(model=df.model.factorize()[0]).plot.scatter(x='val1', y='val2', c='model', colormap='viridis')
    

    enter image description here

    To get a line plot, one option is to pivot model into different columns, interpolate by index and then plot:

    df.pivot('val1', 'model', 'val2').interpolate(method='index').plot.line()
    

    enter image description here

  • Related