我在更改matplotlib图表中图例中的标签方面很费劲。这是我的图:
我想更改图例,以便标签将基于名为“名称”的列中的值。
这是我创建原始图形的方式:
ax = plt.figure()
df.iloc[3000:3005,:].loc[:,float_cols].T.plot(figsize=(10,6))
plt.title('title',size=(20))
plt.ylabel('Y', size=(14))
plt.xlabel('x', size=(14))
这就是我试图将图例更改为列名的方式:
targets = df['name']
ax = plt.figure()
df.iloc[3000:3005,:].loc[:,float_cols].T.plot(figsize=(10,6).label=targets)
plt.title('title',size=(20))
plt.ylabel('Y', size=(14))
plt.xlabel('x', size=(14))
但是没有用。我还尝试了其他方法,例如使用plt.legend,但没有用。
我的最终目标:将图例更改为具有基于这些观测值名称的标签(来自列名称)
使用matplotlib常规plt.plot()
:
import matplotlib.pyplot as plot
import pandas as pd
import numpy as np
x = np.linspace(0, 10, 100)
d = {'col1': np.cos(x), 'col2': np.sin(x), 'col3': np.sin(x) + np.cos(x)}
df = pd.DataFrame(data = d)
plt.figure()
for i in range(df.shape[1]):
plt.plot(x, df.iloc[:,i], label = df.columns[i])
plt.legend()
plt.tight_layout()
plt.show()