geom_text label with by the use of a numerical variable - r

I'd like to label text (it's a variable) using geom_text:
geom_text(aes(as.Date("2018-03-05"), -8), label = A_Statrd)
I get this error:
Fehler: Aesthetics must be either length 1 or the same as the data (31): label
How can I treat a variable as a label?
Text works well. When I use quotation marks, he will write me the text into my graphic. But this is not what I want. I'd like to take a variable. The variable is numeric.
For any tips/advice I thank you very much.

geom_text is going to expect label as an aesthetic, so it expects it will be receiving a column of your dataframe---hence the error about the vector length.
Two options:
One: make a dummy dataframe with this label in it, something like
data.frame(x = as.Date("2018-03-05"), y = -8, label = A_Statrd)
and use that as the data parameter in your call to geom_text.
Or two: the better option, as suggested in one of the comments, is to use annotate instead of geom_text. This is the situation annotate was designed for, where you have a bit of text or other annotation that isn't mapped to your data, but is instead some static piece of information. Use something like
ggplot(...) +
annotate(geom = "text", x = as.Date("2018-03-05"), y = -8, label = A_Statrd)
This assumes that A_Statrd is a variable you have stored elsewhere---that's what it seems like from your question.

Related

ggplot scale_size_manual function doesn't work

I'm new to ggplot, and I'm not sure how to properly use scale_size_manual on groups of data. I tried to show the label at the right of graph, for example "0-200000", "800000+", but it does not show up on the graph.
data %>%
ggplot(aes(year1, imdb_rating)) +
geom_point(aes(colour = multi_language, size = imdb_votes1)) +
scale_size(breaks = c(1,2,3,4),
labels = c('0-200000','200000-400000','400000-800000','800000+'))
enter image description here
if i use scale_size, this is how it shows. If i change scale_size to scale_size_manual, it won't output anything and shows error "
Error: Continuous value supplied to discrete scale"
the glimpse value of imdb_votes1 is
glimpse(data$imdb_votes1) num [1:269] 7993 37573 24169 6725 22375 ...
The data$imdb_votes1 is a continuous variable,so I'm not sure how to deal with it. Any help is appreciated, thank you so much
enter image description here
this is how i want it to be shown, except i change the label and name

Add text to a ggpairs() scatterplot?

dumb but maddening question: How can I add text labels to my scatterplot points in a ggpairs(...) plot? ggpairs(...) is from the GGally library. The normal geom_text(...) function doesn't seem to be an option, as it take x,y arguments and ggpairs creates an NxN matrix of differently-styled plots.
Not showing data, but imagine I have a column called "ID" with id's of each point that's displayed in the scatterplots.
Happy to add data if it helps, but not sure it's necessary. And maybe the answer is simply that it isn't possible to add text labels to ggpairs(...)?
library(ggplot2)
library(GGally)
ggpairs(hwWrld[, c(2,6,4)], method = "pearson")
Note: Adding labels is for my personal reference. So no need to tell me it would look like an absolute mess. It will. I'm just looking to identify my outliers.
Thanks!
It is most certainly possible. Looking at the documentation for ?GGally::ggpairs there are three arguments, upper, lower and diag, which from the details of the documentations are
Upper and lower are lists that may contain the variables 'continuous', 'combo', 'discrete' and 'na'. Each element of thhe list may be a function or a string
... (more description)
If a function is supplied as an option to upper, lower, or diag, it should implement the function api of function(data, mapping, ...){#make ggplot2 plot}. If a specific function needs its parameters set, wrap(fn, param1 = val1, param2 = val2) the function with its parameters.
Thus a way to "make a label" would be to overwrite the default value of a plot. For example if we wanted to write "hello world" in the upper triangle we could do something like:
library(ggplot2)
library(GGally)
#' Plot continuous upper function, by adding text to the standard plot
#' text is placed straight in the middle, over anything already residing there!
continuous_upper_plot <- function(data, mapping, text, ...){
p <- ggally_cor(data, mapping, ...)
if(!is.data.frame(text))
text <- data.frame(text = text)
lims <- layer_scales(p)
p + geom_label(data = text, aes(x = mean(lims$x$range$range),
y = mean(lims$y$range$range),
label = text),
inherit.aes = FALSE)
}
ggpairs(iris, upper = list(continuous = wrap(continuous_upper_plot,
text = 'hello world')))
with the end result being:
There are 3 things to note here:
I've decided to add the text in the function itself. If your text is part of your existing data, simply using the mapping (aes) argument when calling the function will suffice. And this is likely also better, as you are looking to add text to specific points.
If you have any additional arguments to a function (outside data and mapping) you will need to use wrap to add these to the call.
The function documentation specifically says that arguments should be data, mapping rather than the standard for ggplot2 which is mapping, data. As such for any of the ggplot functions a small wrapper switching their positions will be necessary to overwrite the default arguments for ggpairs.

Shiny reactive as ggplot2 series name and legend label?

I want to use a Shiny input as a name in my shiny plot.
Here is my code:
ggplot() +
...
geom_point(data=data.frame(), aes(x=x, y=y, color=paste(input$name)),
size = 3) +
scale_color_manual(values=c("df1"="blue", "df2"="blue",
paste(input$name)="red"))
It doesn't recognize paste(input$name) as a string. Here is the error message:
1512: scale_color_manual(values=c("df1"="blue", "df2"="blue",
1513: paste(input$name)=
^
Anyone know how to properly structure this?
You can't intermix strings and symbols and expressions like you are doing. If you want to use a string in an aes() mapping, use aes_ or aes_string (no need for paste)
aes_string(x="x", y="y", color=input$name)
And you can't put an expression on the left of = in a named vector. Use something like setNames() instead.
values = setNames(c("blue", "blue", "red"), c("df1", "df2", input$name))
As requested above, it would be easier in the future if you include a reproducible example so that possible solutions can be properly tested. This isn't at all Shiny related. This is just how ggplot and R work.

Cannot save plots as pdf when ggplot function is called inside a function

I am going to plot a boxplot from a 4-column matrix pl1 using ggplot with dots on each box. The instruction for plotting is like this:
p1 <- ggplot(pl1, aes(x=factor(Edge_n), y=get(make.names(y_label)), ymax=max(get(make.names(y_label)))*1.05))+
geom_boxplot(aes(fill=method), outlier.shape= NA)+
theme(text = element_text(size=20), aspect.ratio=1)+
xlab("Number of edges")+
ylab(y_label)+
scale_fill_manual(values=color_box)+
geom_point(aes(x=factor(Edge_n), y=get(make.names(true_des)), ymax=max(get(make.names(true_des)))*1.05, color=method),
position = position_dodge(width=0.75))+
scale_color_manual(values=color_pnt)
Then, I use print(p1) to print it on an opened pdf. However, this does not work for me and I get the below error:
Error in make.names(true_des) : object 'true_des' not found
Does anyone can help?
Your example is not very clear because you give a call but you don't show the values of your variables so it's really hard to figure out what you're trying to do (for instance, is method the name of a column in the data frame pl1, or is it a variable (and if it's a variable, what is its type? string? name?)).
Nonetheless, here's an example that should help set you on the way to doing what you want:
Try something like this:
pl1 <- data.frame(Edge_n = sample(5, 20, TRUE), foo = rnorm(20), bar = rnorm(20))
y_label <- 'foo'
ax <- do.call(aes, list(
x=quote(factor(Edge_n)),
y=as.name(y_label),
ymax = substitute(max(y)*1.05, list(y=as.name(y_label)))))
p1 <- ggplot(pl1) + geom_boxplot(ax)
print(p1)
This should get you started to figuring out the rest of what you're trying to do.
Alternately (a different interpretation of your question) is that you may be running into a problem with the environment in which aes evaluates its arguments. See https://github.com/hadley/ggplot2/issues/743 for details. If this is the issue, then the answer might to override the default value of the environment argument to aes, for instance: aes(x=factor(Edge_n), y=get(make.names(y_label)), ymax=max(get(make.names(y_label)))*1.05, environment=environment())

Dimple dPlot color x-axis bar values in R

I'm attempting to set manual colors for Dimple dPlot line values and having some trouble.
d1 <- dPlot(
x="Date",
y="Count",
groups = "Category",
data = AB_DateCategory,
type = 'line'
)
d1$xAxis(orderRule = "Date")
d1$yAxis(type = "addMeasureAxis")
d1$xAxis(
type = "addTimeAxis",
inputFormat = "%Y-%m-%d",
outputFormat = "%Y-%m-%d",
)
The plot comes out looking great, but I would like to manually set the "Category" colors. Right now, it's set to the defaults and I cannot seem to find a method of manually setting a scale.
I have been able to set the defaults using brewer.pal, but I want to match other colors in my report:
d1$defaultColors(brewer.pal(n=4,"Accent"))
Ideally, these are my four colors - the category values I'm grouping on are R, D, O and U.
("#377EB8", "#4DAF4A", "#E41A1C", "#984EA3"))
If I understand correctly, you want to make sure R is #377EB8, etc. To match R, D, O, U consistently to the colors especially across multiple charts, you will need to do something like this.
d1$defaultColors = "#!d3.scale.ordinal().range(['#377EB8', '#4DAF4A', '#E41A1C', '#984EA3']).domain(['R','D','O','U'])!#"
This is on my list of things to make easier.
Let me know if this doesn't work.
The issue with the accepted answer above is that defining an ordinal scale will not guarantee that specific colors are bound to specific categories R, D, O and U. The color mapping will change depending on the input data. To assign each color specifically you can use assignColor like this
d1$setTemplate(afterScript = '<script>
myChart.assignColor("R","#377EB8");
myChart.draw();
</script>')

Resources