ggplot:修改直方图

ggplot: Modify histogram plot

我使用以下代码制作了这个图:

ggplot(all, aes(x = year, color = layer)) +
  geom_histogram(binwidth = 0.5, fill = "white", alpha = 0.5, position = "dodge") +
  scale_x_continuous(breaks = pretty(all$year)) +
  scale_color_discrete(name = "title", labels = c("A","B")) +
  theme_light() +
  theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
        text = element_text(size = 20),
        axis.title.x = element_text(margin = margin(t = 25, r = 0, b = 0, l = 0)),
        axis.title.y = element_text(margin = margin(t = 0, r = 25, b = 0, l = 0)),
        axis.text.x = element_text(angle = 50, hjust = 1, size = 18, color = "black"),
        axis.text.y = element_text(size = 18, color = "black"))

我现在想先更改颜色,使用 viridis 调色板中的颜色。此外,直方图之间有蓝色和红色笔划,我想将其删除。 有人可以帮我更改代码吗? 提前致谢!

测试数据:

year <- runif(10, 2014, 2021)
year <- round(year, 0)
layer <- sample(c("A","B"), size=10, replace=T)
all <- as.data.frame(year,layer)

您似乎想要条形图而不是直方图。

all <- data.frame(year,layer) ## fix the sample data creation

ggplot(all, aes(x = year, fill = layer)) +  ## I think fill looks better...
  geom_bar(position = position_dodge(preserve = "single")) +  ## bar, not histogram
  #scale_x_continuous(breaks = pretty(all$year)) + ## this line just confirmed defaults
  scale_fill_viridis_d() +
  theme_light() ## omitted the rest of the theme as irrelevant for the issue at hand

如果您确实想要轮廓颜色而不是填充,请切换到geom_bar“修复”条形之间的笔划:

ggplot(all, aes(x = year, color = layer)) +
  geom_bar(position = position_dodge(preserve = "single"), fill = NA) +
  scale_color_viridis_d() +
  theme_light() 

谢谢,这是有用的信息!