Here's a python adaptation of the answer from your second link
If you want to change the legend name, you have to use the name
parameter in both of the scale_*_manual
functions.
from plotnine import ggplot, geom_point, aes, stat_smooth, facet_wrap,geom_jitter
from plotnine.data import mtcars
import plotnine as p9
# add a column that combines the two columns
new_mtcars = mtcars
new_mtcars['legend_col'] = ['Gear: {} Vs: {}'.format(gear,vs)
for gear,vs in zip(new_mtcars.gear,mtcars.vs)]
# specify dicts to use for determining colors and shapes
gear_colors = {3:'red',4:'blue',5:'gray'}
vs_shapes = {0:'^',1:'o'}
# make the plot with scale_*_manual based on the gear and vs values
(
ggplot(mtcars, aes('cyl', 'mpg', color='legend_col', shape='legend_col'))
+ geom_jitter()
+ p9.scale_color_manual(values=[[gear_colors[i] for i in list(new_mtcars.gear.unique())
if 'Gear: {}'.format(i) in label][0]
for label in new_mtcars.legend_col.unique()],
labels = list(new_mtcars.legend_col.unique()),
name='My legend name')
+ p9.scale_shape_manual(values=[[vs_shapes[i] for i in list(new_mtcars.vs.unique())
if 'Vs: {}'.format(i) in label][0]
for label in new_mtcars.legend_col.unique()],
labels = list(new_mtcars.legend_col.unique()),
name='My legend name')
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…