Sher
Sher

Reputation: 415

Changing line styles of several lines in matplotlib

I assigned different colors to different lines of plot with following code. I would appreciate if someone could help with assigning individual line styles to each line. Lines should have solid or dashed line styles. adding linestyles = linestyles argument in plot() function throws an error AttributeError: 'Line2D' object has no property 'linestyles'

fig, ax = plt.subplots()
linestyles =['-', '-', '--', '-', '--', '-', '--']
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ['black', 'brown', 'brown', 'orange', 'orange', 'green', 'green'])
new_df_brindabella[['est_fmc', '1h_surface', '1h_profile', '10h_fuel stick',
       '100h debri', 'Daviesia', 'Eucalyptus', 'obs_fmc_mean']].resample("1M").mean().interpolate().plot(figsize=(15,5), 
                       cmap = cmap, ax=ax)

ax.legend(loc='center left', markerscale=6, bbox_to_anchor=(1, 0.4))

Upvotes: 2

Views: 6370

Answers (1)

Reti43
Reti43

Reputation: 9796

The argument is called linestyle. But it would have given you an error anyway if you had tried to pass a list to it like that.

I don't know of a way to pass multiple linestyles in one plot call like you did for the colours, if even possible at all. However, you can set a cycler for various properties for multi-line plots.

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(np.arange(42).reshape((6, 7)))

# Might as well do both colours and line styles in one go
cycler = plt.cycler(linestyle=['-', '-', '--', '-', '--', '-', '--'],
                    color=['black', 'brown', 'brown', 'orange', 'orange', 'green', 'green'],
)
fig, ax = plt.subplots()
ax.set_prop_cycle(cycler)
df.plot(ax=ax)
plt.show()

The only other way I could think of was keeping everything as you did and then fetch the individual lines from the AxesSubplot object and set their linestyle manually.

new_df_brindabella.plot(...)
for line, ls in zip(ax.get_lines(), linestyles):
    line.set_linestyle(ls)

Upvotes: 2

Related Questions