我多次尝试在堆积条形图上绘制温度线数据,但没有成功。我的数据由四列组成,如下所示:站点、频率、电影_状态和温度:
网站 | 频率 | 移动_状态 | 温度 |
---|---|---|---|
站点_1 | 34. | 完全_感动。 | 30 |
站点_2 | 45. | 部分_移动 | 29 |
站点_3 | 55. | 完全搬家 | 29.5 |
这是我生成绘图的代码。
read.csv("Moving_site.csv")
Recovery_Status <- factor(sample(c("Totally_Moved", "Partially_Moved"),
size = 50, replace = TRUE),
levels = c("Totally_Moved", "Partially_Moved")))
Frequency <- sample(0:100, size = 50, replace = TRUE)
Mean_Temp <- sample(0:50, size = 50, replace = TRUE)
Site <- c("Site_1”, “Site_2”, “Site_3”)
data<-read.table(file="Moving _site.txt", header=T)
data
ggplot(data=data, aes(x=Site, y=Frequency, fill=Moving _Status)) + geom_bar(stat ="identity")
ggplot(data, aes(fill=Moving _Status, y=Frequency, x=Site)) +
geom_bar(position="fill", stat="identity") + scale_fill_grey() + scale_y_continuous() +
ggtitle("Movement")+
theme(plot.title = element_text(hjust = 0.5)) +
theme(axis.ticks = element_line(color = 2,
linewidth = 2))
I want to add another y axis to represent the temperature. I tried to add temperature data as a line plot over the stacked bar chart I made already, but it doesn't show up. How can I add a line plot of temperature over the bar chart?
这是一个包含一些伪造数据的示例:
library(tidyverse)
set.seed(123)
data <- data.frame(
Recovery_Status = sample(
c("Totally Recovered", "Partially Recovered", "Totally Dead"),
size = 50, replace = TRUE),
Frequency = sample(0:100, size = 50, replace = TRUE),
Site = sample(
c("Marsa Shagara", "Marsa_Nakary", "Lahmi", "Gorgonia_Reef",
"Keshta", "Shelineat", "Gotta"),
size = 50, replace = TRUE)
)
temps <- data.frame(
Site = c("Marsa Shagara", "Marsa_Nakary", "Lahmi", "Gorgonia_Reef",
"Keshta", "Shelineat", "Gotta"),
Mean_Temp = sample(16:32, size = 7, replace = TRUE)
)
data <- left_join(data, temps, by = "Site")
ggplot(data, aes(x = Site)) +
geom_bar(
aes(fill = Recovery_Status, y = Frequency),
position = "fill", stat = "identity"
) +
scale_y_continuous(
sec.axis = sec_axis(
~ . * 50,
name = "Mean_Temp",
labels = scales::label_number(suffix = "ºC")
)
) +
scale_fill_grey() +
geom_line(
data = data %>%
mutate(
temp_norm = scales::rescale(
Mean_Temp, from = c(0,50), to = c(0, 1))
),
aes(y = temp_norm, group = 1),
color = "red3", linewidth = 1
) +
ggtitle("Coral Recovery")+
theme(plot.title = element_text(hjust = 0.5)) +
theme(axis.ticks = element_line(color = 2, linewidth = 2))