Ggplot2 中有两个变量的两个直方图
Two histograms with two variables in Ggplot2
这是我的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
其中 test_label 是测试值,“xgb_1”是具有预测值的列,id_items 是项目。
我想绘制图表,在其中我可以并排看到某些 id_items 的预测值与真实值。
有超过 100 个,所以我只需要一个子集来绘制(否则会一团糟)。
让我知道!
P.S。最好的办法是转换行中的 test_label 和 xgb1 并添加一个虚拟变量“Predicted/True 值”,但我不知道该怎么做。
我会建议这种方法,重塑数据然后绘图。有更多的数据,它会更好看:
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"))
代码:
#Reshape
dfa %>% pivot_longer(cols = -id_item) %>%
ggplot(aes(x=value,fill=name))+
geom_histogram(position = position_dodge())+
facet_wrap(.~id_item)
输出:
这是使用 geom_errorbar
的另一种方法。也许颜色有点多,但今天是雨天...所以需要一些变化
"%>%" <- 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()
这是我的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
其中 test_label 是测试值,“xgb_1”是具有预测值的列,id_items 是项目。 我想绘制图表,在其中我可以并排看到某些 id_items 的预测值与真实值。 有超过 100 个,所以我只需要一个子集来绘制(否则会一团糟)。 让我知道!
P.S。最好的办法是转换行中的 test_label 和 xgb1 并添加一个虚拟变量“Predicted/True 值”,但我不知道该怎么做。
我会建议这种方法,重塑数据然后绘图。有更多的数据,它会更好看:
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"))
代码:
#Reshape
dfa %>% pivot_longer(cols = -id_item) %>%
ggplot(aes(x=value,fill=name))+
geom_histogram(position = position_dodge())+
facet_wrap(.~id_item)
输出:
这是使用 geom_errorbar
的另一种方法。也许颜色有点多,但今天是雨天...所以需要一些变化
"%>%" <- 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()