如何在箱线图中做边框?

问题描述 投票:0回答:1

这是随机数据

set.seed(123)

# Number of rows in the dataset
num_rows <- 100

# Generate random dataset with 4 columns
random_dataset <- data.frame(
  A = runif(num_rows),          # Random numbers for column A
  B = runif(num_rows),          # Random numbers for column B
  C = runif(num_rows),          # Random numbers for column C
  D = sample(c("Male", "Female", "Child"), num_rows, replace = TRUE)  # Random values for column D
)

# Display the first few rows of the dataset
head(random_dataset)



 library(ggplot2)
    
    # Generate the bar plot with a black border around the bars
    ggplot(random_dataset, aes(x = D, y = A)) +
  geom_bar(stat = "identity",fill = "skyblue", color = "black") +
  geom_errorbar(
    aes(ymin = A - sd_A, ymax = A + sd_A),
    width = 0.2,
    color = "black"
  ) + 
  labs(title = "Bar Plot of Column A",
       y = "Values for Column A",
       x = "Category D") +
  theme_classic()

现在当我运行这些数据时,我的图片看起来像这样enter image description here

我想要的只是带有误差线的正确条形图,并且每个条上只有一个边框

r ggplot2 bar-chart
1个回答
0
投票

我想你需要这个:我们必须做一些预先计算:

library(dplyr)
library(ggplot2)

random_dataset %>%
  summarise(sum_A = sum(A), sd_A = sd(A), .by=D) %>% 
  ggplot(aes(x = D, y = sum_A)) +
  geom_bar(stat = "identity", fill = "skyblue", color = "black") +
  geom_errorbar(aes(ymin = sum_A - sd_A, ymax = sum_A + sd_A), width = 0.1) 

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.