I have the dataframe below:
d1_6b<-structure(list(conm = c("Intl Business Machines Corp", "Intl Business Machines Corp",
"Intl Business Machines Corp", "Intl Business Machines Corp",
"Intl Business Machines Corp", "Intl Business Machines Corp",
"Intl Business Machines Corp", "Intl Business Machines Corp",
"Intl Business Machines Corp", "Intl Business Machines Corp",
"Intl Business Machines Corp", "Facebook Inc", "Facebook Inc",
"Facebook Inc", "Facebook Inc", "Facebook Inc", "Facebook Inc",
"Facebook Inc", "Facebook Inc", "Facebook Inc", "Facebook Inc",
"Facebook Inc"), pr_margin = structure(c(0.236074536151636, 0.240974222754312,
0.247342283292028, 0.241270764202865, 0.246063819469141, 0.237616373668049,
0.205067567567568, 0.195276665108227, 0.219132816524481, 0.219166007751436,
0.208964955175224, 0.593211752786221, 0.560226354082458, 0.232265671055217,
0.498348577235772, 0.499278036258623, 0.459839357429719, 0.536724799189522,
0.57388138636755, 0.523532361474265, 0.491223107062534, 0.459873204211016
), label = "Operating Income Before Depreciation", format.stata = ".0g"),
datadate = structure(c(14974, 15339, 15705, 16070, 16435,
16800, 17166, 17531, 17896, 18261, 18627, 14974, 15339, 15705,
16070, 16435, 16800, 17166, 17531, 17896, 18261, 18627), label = "Data Date", format.stata = "%td", class = "Date")), row.names = c(NA,
-22L), class = c("tbl_df", "tbl", "data.frame"))
and Im trying to combine 2 barplots in one. One below the other. Apparently they should be in the same because they use the same legend like:
My trial:
plot <- ggplot(d1_6b, aes(x = datadate, y = pr_margin))
geom_bar()
facet_wrap(~conm)
theme_minimal()
ylab('Profit Margin')
xlab('Fiscal Year')
plot
but I get Error: stat_count() can only have an x or y aesthetic
.
CodePudding user response:
To fix the error add in stat="identity"
in geom_bar
plot <- ggplot(d1_6b, aes(x = datadate, y = pr_margin))
geom_bar(stat="identity")
facet_wrap(~conm,ncol=1)
theme_minimal()
ylab('Profit Margin')
xlab('Fiscal Year')
plot
CodePudding user response:
Use geom_col
:
ggplot(d1_6b, aes(x = datadate, y = pr_margin))
geom_col(aes(fill = conm))
facet_wrap(~conm, ncol = 1)
theme_minimal()
theme(legend.position = "top")
labs(x = 'Fiscal Year',
y = 'Profit Margin',
fill = element_blank())
From the documentation:
If you want the heights of the bars to represent values in the data, use geom_col() instead.