1

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)))
RJandl
  • 11
  • 1
  • Please don't share data as images because we can't copy/paste that into R so we can't run your code to see what your plot looks like. Share data in a [reproducible format](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) otherwise it will be very difficult to help you. – MrFlick Sep 07 '20 at 21:38

1 Answers1

0

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.

Marianela
  • 35
  • 6