简体   繁体   中英

Showing multiple Line Legends in Matplotlib

I am trying to display all 4 legends of my line graph, with the Column headers serving as the respective Legend names. Is there an elegant way of executing this without having to write individual lines of code to plot and label each column?

Examples of my current data set are as follows:

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

x = pd.Series(np.array([1,2,3,4,5,6,7,8,9,10]))
y = pd.DataFrame(np.random.rand(10,4))
y.columns = ["A","B","C","D"]
fig, ax = plt.subplots(figsize=(10, 7))
ax.plot(x, y, label=True)

Indeed you can use the plot function defined in pandas:

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

x = pd.Series(np.array([1,2,3,4,5,6,7,8,9,10]))
y = pd.DataFrame(np.random.rand(10,4))
y.columns = ["A","B","C","D"]
y['x'] = x
fig, ax = plt.subplots(figsize=(10, 7))
y.plot(ax=ax)

输出图像

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