英文:
How to make base R double barplot in ggplot
问题
I've made the following double marplot in base R, but would like to make the same graph in gig-lot if possible. How would I go about doing this?
我已经在基本的R中制作了以下的双Y轴图,但如果可能的话,我想在gig-lot中制作相同的图表。我该如何操作?
英文:
I've made the following double marplot in base R, but would like to make the same graph in gig-lot if possible. How would I go about doing this?
data <- structure(list(
A= c(53, 39),
B = c(30, 36),
C = c(12, 19),
D = c(5, 6)),
.Names = c("Poor", "Fair", "Good", "Excellent"),
class = "data.frame",
row.names = c(NA, -2L))
attach(data)
print(data)
colors <- c("dodgerblue3","red3")
barplot(as.matrix(data),
main="",
beside = T, ylab = "", ylim = range(0,65), col=colors, border=F)
legend(5,60, legend=c("Fox News", "CNN"),
fill=colors, horiz = T, bty='n')
text(1.5, 55, "53%")
text(2.5, 41, "39%")
text(4.5, 32, "30%")
text(5.5, 38, "36%")
text(7.5, 14, "12%")
text(8.5, 21, "19%")
text(10.5, 7, "5%")
text(11.5, 8, "6%")
答案1
得分: -3
这是我们可以这样做的方式:
library(ggplot2)
library(dplyr)
library(tidyr)
library(forcats)
data %>%
mutate(Group = row_number()) %>%
pivot_longer(cols = -Group) %>%
ggplot(aes(x = fct_inorder(name), y = value, fill = factor(Group))) +
geom_col(position = position_dodge()) +
labs(x = NULL, y = NULL, fill = NULL) +
scale_fill_manual(values = c("dodgerblue3", "red3"), labels = c("Fox New", "CNN")) +
theme_minimal() +
theme(
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
legend.position = c(.95, .95),
legend.justification = c("right", "top"),
legend.box.just = "right",
legend.margin = margin(6, 6, 6, 6),
legend.direction = "horizontal",
axis.text.x = element_text(hjust = 1)
) +
geom_text(
aes(label = paste0(value, "%")),
position = position_dodge(width = 1),
vjust = -0.5
)
英文:
Here is how we could do it:
library(ggplot2)
library(dplyr)
library(tidyr)
library(forcats)
data %>%
mutate(Group = row_number()) %>%
pivot_longer(cols = -Group) %>%
ggplot(aes(x = fct_inorder(name), y = value, fill = factor(Group))) +
geom_col(position = position_dodge()) +
labs(x = NULL, y = NULL, fill = NULL) +
scale_fill_manual(values = c("dodgerblue3","red3"), labels = c("Fox New", "CNN"))+
theme_minimal() +
theme(
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
legend.position = c(.95, .95),
legend.justification = c("right", "top"),
legend.box.just = "right",
legend.margin = margin(6, 6, 6, 6),
legend.direction="horizontal",
axis.text.x = element_text(hjust = 1)
) +
geom_text(
aes(label = paste0(value, "%")),
position = position_dodge(width = 1),
vjust = -0.5
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论