简体   繁体   中英

Two histograms with two variables in Ggplot2

This is my DF :

> head(xgb_1_plot)
   week PRICE id_item food_cat_id test_label xgb_1
2     5    18      60           7          2     2
7     5    21       9           6          5     8
12    5    14      31           4          4     6
21    5    15      25           7         12    12
31    5    14      76           3          4     2
36    5     7      48           8          2     4

Where test_label is the test value, "xgb_1" is the column with the predicted values and id_items are the items. I want to plot graph in which I can see predicted values VS true values side by side for some id_items. There are over 100, so I need just a subset for the plot (otherwise it'll be a mess). Let me know!

PS the best thing would be transform the test_label and the xgb1 in rows and add a dummy variable "Predicted/True value", but I have no idea how to do it.

I would suggest this approach, reshaping data and then plotting. Having more data, it will look better:

library(tidyverse)
#Data
dfa <- structure(list(id_item = c(60L, 9L, 31L, 25L, 76L, 48L), test_label = c(2L, 
5L, 4L, 12L, 4L, 2L), xgb_1 = c(2L, 8L, 6L, 12L, 2L, 4L)), class = "data.frame", row.names = c("2", 
"7", "12", "21", "31", "36"))

Code:

#Reshape
dfa %>% pivot_longer(cols = -id_item) %>%
  ggplot(aes(x=value,fill=name))+
  geom_histogram(position = position_dodge())+
  facet_wrap(.~id_item)

Output:

在此处输入图片说明

Here's a differnt approach using geom_errorbar . Maybe the color thing is a little bit too much, but today is a rainy day ... so was in need of some variety

"%>%" <- magrittr::"%>%"

dat <- dplyr::tibble(id_item=c(69,9,31,25,76,48),
              test_label=c(2,5,4,12,4,2),
              xgb_1=c(2,8,6,21,2,4))

dat %>%
  dplyr::mutate(diff=abs(test_label-xgb_1)) %>%
  ggplot2::ggplot(ggplot2::aes(x=id_item,ymin=test_label,ymax=xgb_1,color=diff)) + 
  ggplot2::geom_errorbar()

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