我正在尝试创建堆积柱形图。
我编写的代码以相反的顺序显示列中的值,并且我无法更改自己的颜色。当我指定我赢得的十六进制时,我得到灰色的列。
您可以看一下吗? 我还附上了我的数据的图片以及我希望图表在 Excel 中的样子,以及我在 R 中的结果。
谢谢你,埃里卡
这是我编写的代码:
col_names <- c("A", "B", "C", "D","E", "F", "G","H") # Adjust as per your data
colnames(data) <- col_names
data_long$A <- factor(data_long$A, levels = rev(levels(data_long$A)))
# Reshape the data into long format
data_long <- tidyr::pivot_longer(data, cols = c(B:H), names_to = "X", values_to = "Value")
ggplot(data_long, aes(x = X, y = Value, fill = A)) +
geom_col(position = "stack") +
labs(x = "X Axis", y = "Y Axis", fill = "Y Axis") +
theme_minimal()
您可以使用
scale_fill_manual()
定义您想要使用的颜色。试试这个
yr = c("<1","1-2","2-3","3-5","5-10","10-20",">20")
A = c(28, 30, 11, 6, 12, 11, 2)
B = 0.9*A
B[7] <- B[7] + 10
C = 0.85 * A
C[7] = C[7] + 15
D = 1.1*A
D[1] = D[1] - 10
E = 1.2*A
E[2] = E[2] - 20
data = data.frame(yr,A,B,C,D,E)
library(colorspace)
# Reshape the data into long format
data_long <- tidyr::pivot_longer(data, cols = c(A:E), names_to = "X", values_to = "Value")
data_long$yr <- factor(data_long$yr, levels = rev(yr)) ## order in which you wish to stack
mycolors <- diverging_hcl(7, "Berlin")
ggplot(data_long, aes(x = X, y = Value, fill = yr)) +
geom_col(position = "stack") +
labs(x = "", y = "%") +
scale_fill_manual(values=mycolors, name= "", breaks = yr) + ### choose your own color
theme_minimal() +
theme(legend.position="bottom") +
guides(fill = guide_legend(nrow = 1))