简体   繁体   中英

Dynamic legend labels in ggplot2

I defined a data structure for storing legend labels as follows (because I want to produce mutliple plots with different data and different labels in a row).

legendlabels <- data.frame(
                    'stadtland'=c("Core City\n(Agglomeration)","Municipality\n(Agglomeration)", "Isolated City", "Rural\nMunicipality"),
                    stringsAsFactors=FALSE)

Now, when I use legendlabels within a ggplot like this,

... + 
scale_colour_hue(name="Type",
                     breaks=as.factor(c(1:4)),
                     labels=legendlabels['stadtland'],
                     l=65) +
...

the legend merely displays "1","2","3","4" for the 4 different labels. However, when I insert the vector directly (undynamically), the strings get displayed correctly:

... + 
scale_colour_hue(name="Type",
                     breaks=as.factor(c(1:4)),
                     labels=c("Core City\n(Agglomeration)","Municipality\n(Agglomeration)", "Isolated City", "Rural\nMunicipality"),
                     l=65) +
...

How can I substitute this?

As I mentioned in my comment,

labels=legendlabels['stadtland']

will return a list of length one, not the atomic vector you are looking for. Instead, you want to use [[ :

labels=legendlabels[['stadtland']]

which returns the element named stadtland from the list (data frames are lists) legendlabels .

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