Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplot:动态对齐几何图形文本标签_R_Ggplot2_Bar Chart - Fatal编程技术网

R ggplot:动态对齐几何图形文本标签

R ggplot:动态对齐几何图形文本标签,r,ggplot2,bar-chart,R,Ggplot2,Bar Chart,我制作了一个漏斗图来显示各个阶段的转换情况a>B>C>D 以下是R代码: library(ggplot2) library(ggthemes) options(scipen = 999) # turns of scientific notations like 1e+40 stage <- c("A","A", "B","B","C","C","D","D") percent <- c(-100,100,-75,75,-50,50,-10,10) funnel_df <-

我制作了一个漏斗图来显示各个阶段的转换情况a>B>C>D

以下是R代码:

library(ggplot2)
library(ggthemes)
options(scipen = 999)  # turns of scientific notations like 1e+40

stage <- c("A","A", "B","B","C","C","D","D")
percent <- c(-100,100,-75,75,-50,50,-10,10)
funnel_df <- data.frame(stage, percent)

# X Axis Breaks and Labels 
brks <- seq(-100, 100, 10)
lbls = paste0(as.character(seq(0, 100, 5), "%"))

# Plot
ggplot(funnel_df, aes(x = stage, y = percent)) +   # Fill column
  geom_bar(stat = "identity", width = .6) +   # draw the bars
  geom_text(data=funnel_df, 
            aes(label= paste(round(percent), '%'), hjust = c(4,4,4,4,4,4,4,1)),
            color='white') +
  scale_y_continuous(breaks = brks,   # Breaks
                     labels = lbls) + # Labels
  coord_flip() +  # Flip axes
  labs(title="Email Campaign Funnel") +
  theme_tufte() +  # Tufte theme from ggfortify
  theme(plot.title = element_text(hjust = .5), 
        axis.ticks = element_blank()) +   # Centre plot title
  scale_fill_brewer(palette = "Dark2")  # Color palette
库(ggplot2)
图书馆(主题)
选项(scipen=999)#科学符号的轮次,如1e+40

阶段绘图的中心始终位于y=0(y,因为您翻转了坐标)。因此,可以通过将文本的y值设置为0来居中,如中所示

ggplot(funnel_df, aes(x = stage, y = percent)) +   # Fill column
  geom_bar(stat = "identity", width = .6) +   # draw the bars
  geom_text(data=funnel_df[1:nrow(funnel_df) %% 2 == 0, ], # only want to positive percents
            aes(y = 0, label= paste(round(percent), '%')), # y = 0 is centered
            color='white') +
  scale_y_continuous(breaks = brks,   # Breaks
                     labels = lbls) + # Labels
  coord_flip() +  # Flip axes
  labs(title="Email Campaign Funnel") +
  theme_tufte() +  # Tufte theme from ggfortify
  theme(plot.title = element_text(hjust = .5), 
        axis.ticks = element_blank()) +   # Centre plot title
  scale_fill_brewer(palette = "Dark2")  # Color palette
产生: