简体   繁体   中英

How can I add data points to my line plot in same colour (matplotlib)?

I have a line plot to which I would like to add original datapoints in the same colour as the lines (which are fine in default). Problem: When I do it for a lot of IDs or datapoints (also missings) I can no longer distinguish to whom that data belong.

import pandas as pd
df = pd.DataFrame({'year': ['1988', '1989', '1990', '1988', '1989', '1990', '1988', '1989', '1990'],
                   'id': ['1', '1', '1', '2', '2', '2', '3', '3', '3'],
                   'money': ['5', '7', '8', '8', '3', '3', '7', '8', '10']}).astype(int)

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()

for i in df.id.unique():
    df[df['id']==i].plot.line(x='year', y='money', ax=ax, label='id = %s'%i)
    df[df['id']==i].plot.scatter(x='year', y='money', ax=ax)
    plt.xticks(np.unique(df.year))   

在此处输入图片说明

Question: How can I access the default color list of my plot.line to use it in plot.scatter ? Or is there another, easier way to highlight the data which constitutes the lines?

There's a marker option in plot.line :

fig, ax = plt.subplots()

for i in df.id.unique():
    df[df['id']==i].plot.line(x='year', 
                              y='money', 
                              marker='o', # this add the data points on the line, with the same color 
                              ax=ax, 
                              label='id = %s'%i)

Output:

在此处输入图片说明

IIUC, you can try, although @QuangHoang is the better solution:

import pandas as pd
df = pd.DataFrame({'year': ['1988', '1989', '1990', '1988', '1989', '1990', '1988', '1989', '1990'],
                   'id': ['1', '1', '1', '2', '2', '2', '3', '3', '3'],
                   'money': ['5', '7', '8', '8', '3', '3', '7', '8', '10']}).astype(int)

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()

color = plt.rcParams['axes.prop_cycle'].by_key()['color']

for i in df.id.unique():
    df[df['id']==i].plot.line(x='year', y='money', ax=ax, label='id = %s'%i)
    df[df['id']==i].plot.scatter(x='year', y='money', ax=ax, color=color[i-1])
    plt.xticks(np.unique(df.year))  

Output: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM