簡體   English   中英

如何在ggplot2中像這樣調整y軸?

[英]How to adjust the the y axis like this in ggplot2?

這是代碼和當前的情節

df <- data.frame(state = c('0','1'),
                                male = c(26287942,9134784),
                                female = c(16234000,4406645))
#output
> df
  state     male   female
1     0 26287942 16234000
2     1  9134784  4406645
library(ggplot2)
library(tidyr)

df_long <- pivot_longer(df, cols = c("female","male"))
names(df_long) <- c('state','sex','observations')
ggplot(data = df_long) +
  geom_col(aes(x = sex, y =observations, fill = state)) + 
   theme(legend.position = c(0.1,0.9),  
   legend.background = element_rect(fill='lightgrey') )

我現在的輸出

我想調整這樣的情節。 (我標記了我想要更改的內容。) 所需圖片

  1. 簡化 y 軸上的科學記錄。
  2. 計算比率(狀態 1 的數量)/(狀態 0 + 狀態 1 的數量)並像這樣繪制。

可能有點復雜,不知道用什么函數。 如果可能的話,誰能告訴我一些相關的功能或例子?

您可以設置options(scipen = 99)以禁用 y 軸上的科學記數法。 我們可以為標簽數據創建一個單獨的數據集。

library(tidyverse)

options(scipen = 99)

long_data <- df %>% 
  pivot_longer(cols = c(male, female), 
               names_to = "sex", 
               values_to = "observations")

label_data <- long_data %>%
  group_by(sex) %>%
  summarise(perc = observations[match(1, state)]/sum(observations), 
            total = sum(observations), .groups = "drop")

ggplot(long_data) + 
  geom_col(aes(x = sex, y = observations, fill = state)) +
  geom_text(data = label_data, 
            aes(label = round(perc, 2), x = sex, y = total), 
            vjust = -0.5) + 
  theme(legend.position = c(0.1,0.9),  
        legend.background = element_rect(fill='lightgrey'))

在此處輸入圖像描述

["

sex <- c('M','F')
y0 <- c(26287942,16234000)
y1 <- c(9134784, 4406645)
y0 <- y0*10^{-7}
y1 <- y1*10^{-7}
ratio <- y1/(y0+y1)
ratio <- round(ratio,2)
m <- t(matrix(c(y0,y1),ncol=2))
colnames(m) <- c(as.character(sex))
df <- as.data.frame(m)
df <- cbind(c('0','1'),df)
colnames(df)[1] <- 'observations'
df
df_long <- pivot_longer(df, cols = as.character(sex))
names(df_long) <- c('state','sex','observations')
df_r <- as.data.frame(df_long)            
df_r <- data.frame(df_r,ratio=rep(ratio,2))
ggplot(data = df_r) +
  geom_col(aes(x =sex, y = observations, fill = state))+
  theme(legend.position = c(0.1,0.9),
        legend.background = element_rect(fill=NULL) )+
  geom_line(aes(x=sex,y=ratio*10),group=1)+
  geom_point(aes(x=sex,y=ratio*10))+
  geom_text(aes(x=sex,y=ratio*10+0.35),label=rep(ratio,2))+
  scale_y_continuous(name =expression(paste('observations(','\u00D7', 10^7,')')),
                     sec.axis = sec_axis(~./10,name='ratio'))

暫無
暫無

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

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