[英]In ggplot, how can I make a grid along x and y axis between categories?
下面是沒有任何panel.grid
繪圖的可重現 R 腳本
require(ggplot2)
library(ggrepel)
# Create the data frame.
sales_data <- data.frame(
emp_name = rep(c("Sam", "Dave", "John", "Harry", "Clark", "Kent", "Kenneth", "Richard", "Clement", "Toby", "Jonathan"), times = 5),
month = as.factor(rep(c("Jan", "Feb", "Mar", "Jan", "Feb", "Mar", "Jan", "Feb", "Mar", "Jan", "Jan"), times = 5)),
dept_name = as.factor(rep(c("Production", "Services", "Support", "Support", "Services", "Production", "Production", "Support", "Support", "Support", "Production"), times = 5)),
revenue = rep(c(100, 200, 300, 400, 500, 600, 500, 400, 300, 200, 500), times = 5)
)
sales_data$month <- factor(sales_data$month, levels = c("Jan", "Feb", "Mar"))
month_vector <- levels(sales_data$month)
number_of_enteries <- nrow(sales_data)
sales_data$month <- as.integer(sales_data$month)
ggplot(sales_data, aes(x = month, y = dept_name)) +
geom_raster(data = expand.grid(sales_data$month, sales_data$dept_name),
aes(x = Var1, y = Var2, width=1, height=1), fill = NA, col = 'gray50', lty = 1) + #default width and height is 1
geom_point(aes(size = revenue, col = revenue),
shape = 16, position = position_jitter(seed = 0), show.legend = F) +
geom_text_repel(aes(label = revenue), size=4, vjust = 1.6, position = position_jitter(seed = 0)) + #try with geom_text
theme_bw() +
theme(
axis.title = element_blank(),
axis.ticks = element_blank(),
plot.background = element_blank(),
axis.line = element_blank(),
panel.border = element_blank(),
panel.grid = element_blank(),
#panel.grid.major.y = element_line(colour = "red"),
#panel.grid.major.x = element_line(colour = "red"),
axis.text = element_text(colour = "blue", face = "plain", size =11)
) +
scale_x_continuous(limits=c(0.5,3.5), expand = c(0,0), breaks = 1:length(month_vector), labels = month_vector)
輸出圖是: 預期情節:
我想沿着 x 和 y 軸有刻度線,如紅線所示。 我嘗試在
theme
使用panel.grid
但由於我自定義添加的scale_x_continuous
它給了我不需要的主要次要軸。 請取消注釋 line panel.grid.major.y = element_line(colour = "red"),
以查看major
網格。
令人驚訝的是,據我所知,在離散類別之間獲取panel.grid
線似乎不是一個好方法。 解決此問題的一種方法是使用hline
和vline
添加這些行:
在您的ggplot
代碼中,添加以下 3 行:
# Remove extra whitespace from y-axis so lines are against the axis
scale_y_discrete(expand = c(0,0)) +
# Add straight lines at each factor level, shifted left/down so they're between values
geom_hline(yintercept = as.numeric(sales_data$dept_name) - 0.5) +
geom_vline(xintercept = as.numeric(sales_data$month) - 0.5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.