在 Plotnine 中隐藏图例中的某些分类元素
Hide certain categorical element from legend in Plotnine
Plotnine 中是否可以隐藏某些图例元素?
mpg_select = mpg[mpg["manufacturer"].isin(pd.Series(["audi", "ford", "honda", "hyundai"]))]
我只选择了4家厂商。但是当我绘制数据时,我仍然看到数据中没有的制造商作为我图例的元素。
(ggplot(mpg_select, aes(x="displ", y="cty"))
+ geom_jitter(aes(size="hwy", color="manufacturer"))
+ geom_smooth(aes(color="manufacturer"), method="lm", se=False)
+ labs(title="Bubble chart")
)
如何只显示我选择的制造商(奥迪、福特、本田和现代)作为我的图例?
这是因为 manufacturer
列是分类的,它仍然包含所有这些类别。您可以从列中删除类别,多余的值将从图例中删除。
from plotnine.data import mpg
desired_manufacturers = ['audi','ford','honda','hyundai']
mpg_select = mpg.loc[mpg['manufacturer'].isin(desired_manufacturers)]
mpg_select['manufacturer_subset'] = pd.Categorical(mpg_select['manufacturer'],
categories=desired_manufacturers)
(ggplot(mpg_select, aes(x="displ", y="cty"))
+ geom_jitter(aes(size="hwy", color="manufacturer_subset"))
+ geom_smooth(aes(color="manufacturer_subset"), method="lm", se=False)
+ labs(title="Bubble chart")
)
Plotnine 中是否可以隐藏某些图例元素?
mpg_select = mpg[mpg["manufacturer"].isin(pd.Series(["audi", "ford", "honda", "hyundai"]))]
我只选择了4家厂商。但是当我绘制数据时,我仍然看到数据中没有的制造商作为我图例的元素。
(ggplot(mpg_select, aes(x="displ", y="cty"))
+ geom_jitter(aes(size="hwy", color="manufacturer"))
+ geom_smooth(aes(color="manufacturer"), method="lm", se=False)
+ labs(title="Bubble chart")
)
如何只显示我选择的制造商(奥迪、福特、本田和现代)作为我的图例?
这是因为 manufacturer
列是分类的,它仍然包含所有这些类别。您可以从列中删除类别,多余的值将从图例中删除。
from plotnine.data import mpg
desired_manufacturers = ['audi','ford','honda','hyundai']
mpg_select = mpg.loc[mpg['manufacturer'].isin(desired_manufacturers)]
mpg_select['manufacturer_subset'] = pd.Categorical(mpg_select['manufacturer'],
categories=desired_manufacturers)
(ggplot(mpg_select, aes(x="displ", y="cty"))
+ geom_jitter(aes(size="hwy", color="manufacturer_subset"))
+ geom_smooth(aes(color="manufacturer_subset"), method="lm", se=False)
+ labs(title="Bubble chart")
)