简体   繁体   中英

seaborn legend title position

I want to draw a graph with seaborn, however, the legend title name of my graph always stay in the same row with other legend names, such as:

在此处输入图片说明

the code I use is like:

test = pd.read_csv('test.csv')
ax = sns.lineplot(x='hour',y='travel_time',hue='Name',data=test)
ax.legend(shadow=True, fancybox=True, ncol = 2, fontsize = 14)

The data is available through:

https://knightsucfedu39751-my.sharepoint.com/:x:/g/personal/peili_knights_ucf_edu/ES8Y98bYZndNulxVKSsaHRgB67TYkAvg4uLwWszDiJvAzQ?e=oumJpK

I want to put the legend title in the center of the legend area, Does anybody know how to solve this problem? Thank you!

Of course you can tweak the legend by removing the fake title entry and adding a real title. That's in the end more cumbersome than just using matplotlib for your line plot, because that offers the centered title for free.

This would require one more line of code and might look like

for n, grp in df.groupby("hue"):
    plt.plot("xData", "yData", data=grp, label=n)
plt.legend(shadow=True, fancybox=True, ncol = 2, title="Name")

For completeness, a runnable example:

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

df = pd.DataFrame({"xData" : np.sort(np.cumsum(np.random.randn(10,10), axis=1), axis=1).flatten(),
                   "yData" : np.cumsum(np.random.randn(10,10), axis=1).flatten(),
                   "hue" : np.array([[f"Label {i+1}"]*10 for i in range(10)]).flatten()})

for n, grp in df.groupby("hue"):
    plt.plot("xData", "yData", data=grp, label=n)
plt.legend(shadow=True, fancybox=True, ncol = 2, title="Name")

plt.show()

resulting in

在此处输入图片说明

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