I'm writing a dissertation and I'd like to construct a "professional" horizontal barplot. It should seem something like this in terms of the layout, but the colors are not appropriate for formal writing:
Let me make a simple example on how I tried to code it:
df=data.frame(Country=c("USA","DEU","CHN","ITA","JPN"), Stock=c(1000,500,15000,300,600))
y=df$Country
x=df$Stock
barplot(y~x,horiz=TRUE)
The problem is that not all the countries are displayed on the y-axis and how can I make the stock number values appear to the right of the bar as per the picture above?
CodePudding user response:
Read ?barplot
, function has many nice features. For the country labels use a named vector a
to avoid confusing the allocations. The bar labels can be done with text
.
pdf('plot.pdf', width=12, height=4)
par(mar=c(5, 8, 4, 6))
a <- setNames(c('United States', 'Germany', 'China', 'Italy', 'Japan'), df$Country)
b <- barplot(df$Stock, horiz=TRUE, names.arg=a[df$Country], xlab='\'000 of units',
col=4, border=4, axes=F,
main='Annual installations of industrial robots\n15 largest markets 2019')
## bar labels
text(df$Stock 100, b, labels=df$Stock/1e3, adj=0, xpd=TRUE, col=4)
## special x axis
mtext(axTicks(1)/1e3, 1, 1, at=axTicks(1))
dev.off()
The dimensions of the plot, and thus bar widths can be controlled by width
and height
parameters of pdf
device. Check journal guide which format is needed. Find your plot in your working directory (use getwd()
).
Data:
df <- structure(list(Country = c("USA", "DEU", "CHN", "ITA", "JPN"),
Stock = c(1000, 500, 15000, 300, 600)), class = "data.frame", row.names = c(NA,
-5L))
CodePudding user response:
You could use the following code:
library(ggplot2)
library(dplyr)
df <- data.frame(country = c('China', 'Japan', 'United States'),
value = c(140.5, 49.9, 33.3))
df %>%
ggplot(aes(x = reorder(country, value), y = value))
geom_col(fill = 'Sky Blue')
geom_text(aes(label = value), color = 'Sky Blue', hjust = -0.1)
scale_y_continuous(breaks = scales::pretty_breaks(10), limits = c(0, 160))
coord_flip()
labs(x = '', y = bquote("'000 of units"), title = 'Annual installations of industrial robots \n 15 largest markets 2019')
theme_grey()
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.ticks.length = unit(0, "points"))
Created on 2022-10-01 with reprex v2.0.2