Error : Aesthetics must be either length 1 or the same as the data (70): x, y, fill

Below is my code. Need help. Please assist. Getting an error

Error : Aesthetics must be either length 1 or the same as the data (70): x, y, fill

provider <- dfPatientControl$Provider
df <- data.frame(
value <- factor(provider, levels = provider),
percent <- c(dfPatientControl$PercentControl),
fill <- factor(ifelse(percent>=70, "Above 70%","Below 70%"), levels = c("Above 70%","Below 70%") ),
undercontrol <- c(dfPatientControl$TotalUnderControl)
)
df <- df[which(df$percent > 0),]
View(df)
if(is.data.frame(df)){
if(nrow(df) > 0){
p <- ggplot(df,aes(x=value,y=percent, fill = fill))+
geom_bar(stat = "identity",width=0.9,colour = "black")+
geom_text(aes(label=paste0(prettyNum(percent, big.mark = ','), "%","(",undercontrol,")")),size = 3.5, position = position_stack(vjust = 0.9),colour = "black")+
xlab("Providers") + ylab("Percent") +
labs(caption="Powered by OMS Trace Analytics ®")+
scale_fill_manual(name = "Legend", values=c("Above 70%"="forestgreen","Below 70%"="firebrick3")) +
ggtitle("BP Control By Provider")+
theme_classic()+
theme(
plot.title = element_text(color="black", size=14, face="bold"),
axis.text.x =element_text(size=14),
axis.text.y =element_text(size=14),
axis.title.x = element_text(size=14,face="bold"),
axis.title.y = element_text(size=14,face="bold"),
legend.text=element_text(size=14),
legend.title=element_text(size=14, face = "bold"),
panel.grid.major = element_blank(), #remove background box,color
panel.grid.minor = element_blank(),#remove background box,color
panel.background = element_blank(), #remove background box,color
axis.line = element_line(colour = "black"))
p+ coord_flip(ylim = c(25,100))
}
else{
showNotification("Please select different provider. No data available" , type = "message")

Hi @abdul.hameed,

it will be difficult to debug this without a reproducible example (reprex). We have no idea how the variable df ends up looking before you try to pass it into ggplot. You can see how to create a reprex here:

1 Like

This can't possibly work? the statement

df <- data.frame(
  value <- factor(provider, levels = provider),
  percent <- c(dfPatientControl$PercentControl),
  fill <- factor(ifelse(percent>=70, "Above 70%","Below 70%"), levels = c("Above 70%","Below 70%") ),
  undercontrol <- c(dfPatientControl$TotalUnderControl)
)

can only execute if percent is defined as a global variable, you cannot use a field from the data frame under construction to make new fields - ie you cant use df$percent while creating df (the problem will be with the fill <- factor(ifelse(percent >=...)) statement).

1 Like