r - 从 x 轴移除 1990 年到 2010 年之间的中间年份
问题描述
我是 R 的初学者,所以如果这是一个非常基本的问题,我提前道歉。
我正在绘制一个箱线图,显示 1990 年和 2010 年的条形类型及其各种数量。这里有两个问题:
- 我希望删除 1980、2000、2020 年。我尝试使用
scale_x_discrete("1990","2010")
但它似乎不起作用。 - 底部的图例列出了条的名称。但是,我希望
.
用空格替换。例如,更改mid.channel.bar
为Mid-channel bar
.
library(ggplot2)
library(tidyr)
library(reshape2)
barCount <- tibble::tribble(
~Year, ~Lateral.bar, ~Bar.accreted.to.island, ~Mid.channel.bar,
1990, 105, 134, 62,
2010, 102, 189, 102
)
df2 <- melt(barCount, id="Year")
barPlot <- ggplot(df2, aes(Year,value)) +
geom_bar(aes(fill=variable),position="dodge",stat="identity") +
labs(y="Quantity",fill="")+
scale_fill_manual("Legend",values=c("Lateral.bar"="khaki4","Bar.accreted.to.island"="Khaki2",
"Mid.channel.bar"="ivory"))
#modifying axis
barPlot <- barPlot + theme(
axis.title.x = element_blank(),
axis.title.y = element_text(size=14),
axis.text.x = element_text(size=14),
legend.position="bottom"
)
barPlot
解决方案
如果您将年份列视为一个因素,ggplot 将为您提供所需的图。加上变量列上的 str_replace_all 会将点交换为空格:
library(reshape2)
library(tidyverse)
barCount <- tibble::tribble(
~Year, ~Lateral.bar, ~Bar.accreted.to.island, ~Mid.channel.bar,
1990, 105, 134, 62,
2010, 102, 189, 102
)
df2 <- melt(barCount, id="Year") %>%
mutate(
Year = Year %>% as.factor(),
variable = variable %>% str_replace_all("\\.", " ")
)
barPlot <- ggplot(df2, aes(Year,value)) +
geom_bar(aes(fill=variable),position="dodge",stat="identity") +
labs(y="Quantity",fill="")+
scale_fill_manual("Legend",values=c("Lateral bar"="khaki4","Bar accreted to island"="Khaki2","Mid channel bar"="ivory"))
#modifying axis
barPlot <- barPlot + theme(
axis.title.x = element_blank(),
axis.title.y = element_text(size=14),
axis.text.x = element_text(size=14),
legend.position="bottom"
)
barPlot
推荐阅读
- php - Laravel 语言环境不采用其他日期格式
- python - 如何回复我输入的频道之外的消息?
- javascript - Vuejs - 通过 lodash 去抖动,传递“等待”参数
- oracle - 如何在目标中识别附加到目标 Oracle 表且随后从其数据源中删除的数据记录?
- r - 如何根据从外部数据框中检索数据的公式添加列?
- java - JNI MattoBitmap 异常
- reactjs - 功能组件定义范围导致应用程序无法正常工作,但我不明白为什么
- javascript - 天数停止在零
- python - Exclude zero from np.linspace in one line
- go - 由于间接导入相同的依赖项,防止 Go 模块覆盖直接依赖项版本