# Load the required library
library(grid)
# Create the data frame
eyecolor <- tibble(
eye = c("Pruun", "Pruun", "Sinine", "Sinine", "Helepruun", "Helepruun", "Roheline", "Roheline"),
gender = c("Mees", "Naine", "Mees", "Naine", "Mees", "Naine", "Mees", "Naine"),
count = c(98, 122, 101, 114, 47, 46, 33, 31)
)
# Prepare the x, y, and fill variables for the plot
x_vals <- eyecolor$count
y_vals <- eyecolor$gender
fill_vals <- eyecolor$eye
# Set up the plotting area
grid.newpage()
pushViewport(viewport(margins = c(0.5, 0.5, 1, 1)))
# Define the limits for the axes
xlim <- range(x_vals)
ylim <- c(0, length(unique(y_vals)))
# Create the x-axis
xaxis <- xaxisGrob(at = pretty(xlim), label = pretty(xlim))
xaxis$children[[2]]$gp$cex <- 0.8 # Adjust font size
# Create the y-axis
yaxis <- yaxisGrob(at = seq(0, length(unique(y_vals)), by = 1), label = unique(y_vals))
yaxis$children[[2]]$gp$cex <- 0.8 # Adjust font size
# Create the barplot
barchart <- barplot(x_vals, horiz = TRUE, xlim = xlim, ylim = ylim, width = 0.5, col = fill_vals)
# Add labels to the bars
labels <- sprintf("%d", x_vals)
text(barchart, y_vals, labels, adj = c(0.5, -0.5), col = "white")
# Add the legends for the eye color
legend <- legendGrob(labels = unique(fill_vals), pch = 15, col = unique(fill_vals),
cex = 0.8, x = 0.7, y = 0.6, title = "Eye Color")
# Draw the plot
grid.draw(
vpTree(
viewport(layout = grid.layout(nrow = 1, ncol = 2, widths = unit(c(2, 1), c("null", "null")))),
xaxis,
vpList(vpBarplot(xaxis = xaxis, yaxis = yaxis, draw = FALSE), barchart),
vpList(viewport(layout.pos.row = 1, layout.pos.col = 2), legend)
)
)
This code will create a barplot with the x-axis representing the count, the y-axis representing the gender, and the color representing the eye color. The grid package is used to set up the plotting area, create the axes, add labels to the bars, and include a legend for the eye color.