簡體   English   中英

如何從ggplot2中的列中為某些值繪制條形圖? 將從數據框中自動選擇值

[英]How to plot bar graph for certain values from the column in ggplot2? Values will be selected automatically from the data frame

我有一個包含 3 列(Year、rain、temp)的數據集,如下所示

  Year      tem     rain
1 1901 24.81962 202.7350
2 1902 24.67261 195.4762
3 1903 24.82354 188.1156
4 1904 24.62806 204.1724
5 1905 24.20550 233.8594
6 1906 24.78262 172.8214 

現在,我想繪制tempyear的關系圖year但不是所有year值。 例如,只有19101920等。

在閱讀了StackOverflow給出的一些帖子后,我編寫了這段代碼

plot_rain <- ggplot(subset(data=aggdata, Year %in% c("1901" , "1910")))+
             geom_line(aes(x=Year, y=tem, color=factor(Year)))+
  theme_minimal()+
  xlab("Year")+
  ylab("Temperature")+
  ggtitle("Temp according to Year") 
ggplotly(plot_rain)

它顯示Error in Year %in% c("1901", "1910") : object 'Year' not found

我該怎么做才能解決這個問題? 我搜索了Google StackOverflow但問題和解決方案似乎與我的不同!

但是,是否可以根據范圍自動增加c()的值? 比如1901, 1910, 1920, ...

我可以為您解決子集問題,盡管我不確定您希望如何按年份為每一行着色,如果年份是您的 y 軸,所以我刪除了這部分:

plot_rain <- ggplot(data=aggdata[aggdata$Year %in% c(1901,1903,1905),])+
  geom_line(aes(x=Year, y=tem))+
  xlab("Year")+
  ylab("Temperature")+
  ggtitle("Temp according to Year") 

在此處輸入圖片說明

離散 x 軸的更新

對於離散的 x 軸,我們必須考慮年份變量。


plot_rain <- ggplot(data=aggdata[aggdata$Year %in% c(1901,1903,1905),],
                    aes(x=factor(Year), y=tem)) +
  geom_line(group=1) +
  xlab("Year") +
  ylab("Temperature") +
  ggtitle("Temp according to Year") 

plot_rain

您嘗試使用的subset函數做了一些不同的事情。 要選擇年份,只需根據所需的aggdata$Year向量檢查aggdata$Year列。 然后繪圖工作。 在此處輸入圖片說明

如果您只想顯示您選擇的年份,我不確定折線圖是否是可視化數據的最佳方式。 由於數據中的差距與一條線相連,因此人們很容易假設線上的每個點都代表(或估計)一年。 如果您明確希望從可視化中排除年份,我會將數據表示為條形圖。

# init
"%>%" <- magrittr::"%>%"

# your data
dat <- dplyr::tibble(Year=1901:1906,
                     tem=c(24.81962,24.67261,24.82354,24.62806,24.20550,24.78262),
                     rain=c(202.7350,195.4762,188.1156,204.1724,233.8594,172.8214))

# define range for filtering years
min <- 1901
max <- 1904

# plot data: filter years between min, max 
# and transform year to factor (as you want a descrete x-axis)
dat %>%
dplyr::filter(dplyr::between(Year,min,max)) %>%
dplyr::mutate(Year=factor(Year)) %>%
ggplot2::ggplot(ggplot2::aes(x=Year,y=tem,fill=Year)) + 
ggplot2::geom_bar(stat="identity") +
ggplot2::theme_minimal() + 
ggplot2::labs(title="Temp according to Year",
              x="Year",
              y="Temperature")

在此處輸入圖片說明

是的,我也同意@sambold,你應該試試bar plot 但是,我對@Julian_Hn 代碼進行了一些更改。

plot_rain <- ggplot(data=aggdata[aggdata$Year %in% c(1901,1910, 1920, 1930, 1940, 1950),], 
           aes(x=factor(Year), y=tem, fill=factor(Year)))+
           geom_bar(stat="identity", width = 0.5, group=1)+
           theme_minimal()+
           xlab("Year")+
           ylab("Temperature")+
          ggtitle("Temp according to Year") 
       ggplotly(plot_rain)

我不知道,你如何能做到自動遞增值year 陰謀

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM