Home > Enterprise >  R: item name missing in the plot legend
R: item name missing in the plot legend

Time:12-29

With this code I get the plot I want

d <- density(mydata$item1)
plot(d)

enter image description here

This code is the same, but omits N/As. And there is a flaw in the plot's legend. As you can see, it doesn't tell what item is plotted, (x = .)

enter image description here

Can you tell where is the matter and how to fix it? Thank you for your help.

My data

structure(list(item1 = c(5, 5, 5, 5, 4, 4, 2, 1, 3, 4, 4, 3, 
2, 5, 2, 4, 4, 3, 6, 5, 3, 2, 5, 3, 3, 1, 3, 5, 1, 3, 2, 6, 3, 
5, 4, 4, 3, 5, 6, 3, 2, 6, 6, 5, 2, 2, 2, 3, 3, 3), item2 = c(5, 
4, 5, 1, 2, 2, 3, 2, 2, 2, 2, 3, 2, 5, 1, 4, 4, 3, 3, 5, 3, 2, 
4, 4, 3, 4, 4, 3, 7, NA, 2, 4, 2, 4, 2, 3, 5, 3, 5, 3, 2, 6, 
6, 7, 2, 3, 2, 3, 1, 4), item3 = c(5, 5, 6, 7, 3, 4, 5, 2, 2, 
6, 4, 2, 5, 7, 1, 2, 4, 5, 6, 6, 5, 2, 6, 5, 6, 4, 6, 4, 6, 4, 
6, 5, 5, 6, 6, 6, 5, 6, 7, 5, 5, 7, 7, 6, 2, 6, 6, 6, 5, 3)), row.names = c(NA, 
-50L), class = c("tbl_df", "tbl", "data.frame"))

CodePudding user response:

Use the main = argument inside plot to make the title say whatever you want it to.

Data$item2 %>%
  na.omit() %>%
  density() %>%
  plot(main = 'Density of Data$item2')

enter image description here

CodePudding user response:

you had a little typo in your code as the density() call was piped into a plot call refering to the variable it was been written to ... this might have resulted in the strange plot.

In general the density() function won't work with NA values acording to the enter image description here

Possibly you can substitute, interpolate or impute the NA values so that you do not have to remove them for the denstiy() call. Though this obviously epends on your data, context and goals.

  • Related