Reputation: 45
I built a graph and used the coord_polar
function. However, the x labels are too long, so I used the str_wrap()
function from the stringr
library to wrap them. Unfortunately when they are plotted, the text in every label is centered.
I want the text IN the labels to be aligned to the left, normally this is done with the hjust
function in theme()
, but when using coord_polar()
it does not work. What am I doing wrong?
Data:
preguntas = c("Mi superior restringe mis posibihdlidades de comunicarme,hablar o reunirme con él",
"Me ignoran, me excluyen o me hfacen el vacio, fingen no verme o me hacfen invisible",
"Me interrumpen continuamente impidiendo expfresarme","Me fuerzan a realifzar trabajos que van contra mis principios o mi ética",
"Evalúan mi trabajo de manera inequitativfa o de forma sesgada","Me dejan sifn ningún trabajo que hacer, ni siquiera a iniciativa propia",
"Me asignan tareas o trabajos absurdos o sin sentido","Me impiden que adopte flas medidas de seguridad necesarias para realizar mi trabajo con la debida seguridad",
"Mi superior restringe mis posibilidades de comunicarme, hablar o reunirme conf él",
"Me ignoran, me excluyen o me hacen el vacio, fingen no verme o me hacen invisifble",
"Me interrumpen continuamente impidiendo expresarme","Me fuerzan a realizar trabfajos que van contra mis principios o mi ética",
"Evalúan mi trabajo de manera idnequitativa o de forma sesgada","Me dejan sin ningfún trabajo que hacer, ni siquiera a iniciativa propia",
"Me asignan tareas o trabajos absurdos o sin sefntido","Me impiden que adopte las mfedidas de seguridad necesarias para realizar mi trabajo con la debida seguridad",
"Mi superior restringe mis posibilidades de comufnicarme", "hablar o reunirme con éfl",
"Me ignoran, me excluyen o me hacen el vacio, fingen no verme o me hacen invisiblfe",
"Me interrumpen continuamente impidiendo expresarmfe","Me fuerzan a realizar trabajfos que van contra mis principios o mi ética",
"Evalúan mi trabajo de manera inequitativa o de fforma sesgada","Me dejan sin ningúnf trabajo que hacer, ni siquiera a iniciativa propia",
"Me asignan tareas o trabajos absurdos o sin senftido","Me impiden que adopte las medfidas de seguridad necesarias para realizar mi trabajo con la debida seguridad",
"Mi superior restringe mis posibilidades de comfunicarme, hablar o reunifrme con él",
"Me ignoran, me exclujyen o me hacen el vacio, ffingen no verme o me hacenf invisible",
"Me interrumpen continuamente impidiendo exprfesarme","Me fuerzan a realizfar trabajos que van contra mis principios o mi ética",
"Evalúan mi trabajo de manera inequitativa of de forma sesgada","Me dejan sfin ningún trabajo que hacer, ni siquiera a iniciativa propia",
"Me asignan tareas o trabajos absurdos o sifn sentido","Me impiden que adoptfe las medidas de seguridad necesarias para realizar mi trabajo con la debida seguridad",
"Mi superior restringe mis posibilidades dfe comunicarme, hablar o reunirme cfon él",
"Me ignoran, me excluyen o me hacen el vafcio, fingen no verme o me hacen invifsible",
"Me interrumpen continuamente impidiendof expresarme","Me fuerzan a realizar trfabajos que van contra mis principios o mi ética",
"Evalúan mi trabajo de manera inequitatfiva o de forma sesgada","Me dejan sin nifngún trabajo que hacer, ni siquiera a iniciativa propia",
"Me asignan tareas o trabajos absurdosf o sin sentido","Me impiden que adopte lasf medidas de seguridad necesarias para realizar mi trabajo con la debida seguridad",
"Evalúan mi trabajo de magnera inequitatfiva o de forma sesgada","Me dejan siin nifngún trabajo que hacer, ni siquiera a iniciativa propia")
valores = floor(runif(43, min=1, max=6))
dataset = data.frame(preguntas, valores)
Code:
library(ggplot2)
library(stringr)
dataset$preguntasCortas = str_wrap(dataset$preguntas, width = 8)
ggplot (data = dataset,
aes(x = preguntasCortas, y = valores, fill = valores)
) +
geom_bar(width = .4, stat = "identity", na.rm = TRUE)+
scale_fill_gradient(low = "gray", high = "red", limits = c(1, 6)) +
coord_polar() +
scale_y_discrete(limits = c(0,7)) +
theme(
axis.text.y = element_blank(),
axis.text.x = element_text(angle = 45, vjust = 0,hjust = 0),
legend.title = element_blank(),
legend.text = element_text(size = 10),
axis.title = element_blank(),
axis.ticks = element_blank(),
panel.background = element_rect(fill = "transparent", color = NA),
plot.margin = unit(c(-.1, -.1, -.1, -.1), "cm"),
text = element_text(
family = "Century Gothic", size=5, color = "#595959"
)
)
Upvotes: 2
Views: 242
Reputation: 29085
In polar coordinates, the hjust
/ vjust
parameter values are hard-coded to 0.5 in CoordPolar$render_fg
(See source code here).
You can get around it by defining your own version of CoordPolar
that codes hjust
differently in render_fg
, & define a coord_polar2()
function that calls on that instead of the original CoordPolar
:
CoordPolar2 <- ggproto("CoordPolar2",
CoordPolar,
render_fg = function (self, panel_params, theme) {
if (is.null(panel_params$theta.major)) {
return(element_render(theme, "panel.border"))
}
theta <- ggplot2:::theta_rescale(self, panel_params$theta.major, panel_params)
labels <- panel_params$theta.labels
theta <- theta[!is.na(theta)]
ends_apart <- (theta[length(theta)] - theta[1])%%(2 * pi)
if (length(theta) > 0 && ends_apart < 0.05) {
n <- length(labels)
if (is.expression(labels)) {
combined <- substitute(paste(a, "/", b), list(a = labels[[1]],
b = labels[[n]]))
}
else {
combined <- paste(labels[1], labels[n], sep = "/")
}
labels[[n]] <- combined
labels <- labels[-1]
theta <- theta[-1]
}
grid::grobTree(if (length(labels) > 0)
ggplot2:::element_render(theme,
"axis.text.x",
labels,
unit(0.45 * sin(theta) + 0.5, "native"),
unit(0.45 * cos(theta) + 0.5, "native"),
hjust = 0, # hjust = 0.5,
vjust = 0.5),
ggplot2:::element_render(theme, "panel.border"))
})
coord_polar2 <- function (theta = "x", start = 0, direction = 1, clip = "on") {
theta <- match.arg(theta, c("x", "y"))
r <- if (theta == "x")
"y"
else "x"
ggproto(NULL,
CoordPolar2, #CoordPolar,
theta = theta, r = r, start = start,
direction = sign(direction), clip = clip)
}
Usage example (I simplified the code & took only the first few rows of data for illustration):
p <- ggplot(data = dataset[1:8, ], # first 8 rows
aes(x = preguntasCortas, y = valores, fill = valores)) +
geom_col(width = .4, na.rm = TRUE)+
scale_fill_gradient(low = "gray", high = "red", limits = c(1, 6)) +
scale_y_discrete(limits = c(0,7)) +
theme_void() +
theme(axis.text.x = element_text(size = 5, lineheight = 0.9, angle = 45))
cowplot::plot_grid(
p + coord_polar(),
p + coord_polar2(),
nrow = 1,
labels = c("Original", "New")
)
Upvotes: 1