简体   繁体   中英

R lattice — unexpected legend

I want to graphically compare carbon pools under different forms of land use. I am reading in my data, later I remove a factor level.

However, when I display the data the legend does not work. The first legend symbol has no label, and the deleted factor (SPEZIALKULTUREN) is still shown.

how can I control the legend?

A sample of the data is shown below enter image description here

enter image description here

agdata <- read.csv("C:/Jandl/LfdProjekte/2017FAO/2020Paper/Agdata.csv", header =  FALSE, sep = ";", dec = ",")
colnames(agdata) <- c("State","AgType","Cpool")

agdata$Cpool <- as.numeric(agdata$Cpool)

levels(agdata$AgType)[levels(agdata$AgType)=="ACKERLAND"] <- "crop"
levels(agdata$AgType)[levels(agdata$AgType)=="ALMEN"] <- "alpine meadow"
levels(agdata$AgType)[levels(agdata$AgType)=="EXTENSIVES GRÜNLAND *"] <- "extens grassland"
levels(agdata$AgType)[levels(agdata$AgType)=="INTENSIVES GRÜNLAND**"] <- "intens grassland"
levels(agdata$AgType)[levels(agdata$AgType)=="WEINGARTEN***"] <- "vineyard"

#dropping SPEZIALKULTUREN
agdata <- subset(agdata,agdata$AgType !="SPEZIALKULTUREN")

agdata <- subset(agdata,agdata$State !="")
agdata <- subset(agdata,agdata$State !="Wien")


library(lattice)

colors = c("lightsalmon3", "lightgoldenrod2", "cadetblue4", "yellow", "red", "blue")

barchart(
data = agdata,
origin = 0,
Cpool ~ State,
groups = AgType ,
xlab = list (
label = "State",
font = 2,
cex = 1),
ylab= list (
label = "C pool t/ha",
font = 2,
cex = 1),
#ylim=c(0,25),
labels = TRUE,
auto.key = list(space="top", columns= 3),
par.settings = list(superpose.polygon = list(col = colors)))

I am not sure, but it happened to me sometimes that, when using the subset function, removed factors remain empty in the dataframe and will occasionally show on some plots. For example, consider this simple dataset named "myexample":

> myexample 
  var1 var2
1    1    a
2    5    a
3    6    b
4    3    b
5    7    c

Now I can subset it to keep only rows where var2 is either a or b

> myexample2<-subset(myexample, var2=="a" | var2=="b")
> myexample2
  var1 var2
1    1    a
2    5    a
3    6    b
4    3    b
> levels(myexample2$var2)
[1] "a" "b" "c"

It will look like "c" was dropped, but it is still there. To properly get rid of it, you can use the function droplevels()

> myexample2<-droplevels(myexample2)
> myexample2
  var1 var2
1    1    a
2    5    a
3    6    b
4    3    b
> levels(myexample2$var2)
[1] "a" "b"

And now it is really gone. Maybe give it a try and see if at least the removed factor is no longer in the plot.

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