R: Add text to plots in lower rightern corner outside plot area
plot(1)
title(sub="hallo", adj=1, line=3, font=2)
Add text outside plot area
I'm not entirely sure what you're trying to do so this may or may not generalise well.
That said, one possibility is to use annotate
with coord_cartesian(clip = "off")
to allow text outside the plot area.
ggplot(mtcars, aes(mpg, cyl, color = vs)) +
geom_line() +
annotate("text", x = 12.5, y = 3.5, label = "Arbitrary text") +
coord_cartesian(ylim = c(4, 8), clip = "off")
R: Add Text(field) outside of Plotting Area
You can create some space around the plot with theme(plot.margin = ...
then simply add a textGrob over your completed plot.
# plot as above ... +
theme(plot.margin = margin(30, 30, 30, 30))
library(grid)
grid.draw(grid.text(label = "A",
x = unit(0.05, "npc"),
y = unit(0.9, "npc"),
gp = gpar(fontsize = 30)))
Adding text outside the ggplot area
You can place text below plot area with labs(caption = "text")
, but you can't place captions on top of the plot. However, you could use subtitles labs(subtitle = "text")
to produce a similar visual of captions on the top.
To further control the aspect of both options use theme(plot.caption = element_text(...), plot.subtitle = element_text(...))
. Type ?element_text
in your console to get all the options for text formatting.
For example:
library(ggplot2)
df <- data.frame(x = rnorm(50), y = rnorm(50))
ggplot(df, aes(x, y)) +
geom_point() +
labs(subtitle = "Your text here", caption = "Your text here") +
theme(plot.caption = element_text(colour = "red", hjust = 0, angle = 15),
plot.subtitle = element_text(size = 18, face = "bold", hjust = 0.8))
How to annotate a point outside the plot itself?
You can do so in three steps:
- adjust margins to make room for the text using
fig.update_layout(margin=dict())
- add line using
fig.add_shape()
- add text outside plot using
add_annotation(yref='paper', y=1.06)
wherey > 1
places the annotation outside the boundaries of the axes.
See code snippet for details
Plot:
Complete code:
# imports
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from IPython.core.display import display, HTML
import plotly.figure_factory as ff
import plotly.graph_objs as go
# setup
display(HTML("<style>.container { width:50% !important; } .widget-select > select {background-color: gainsboro;}</style>"))
init_notebook_mode(connected=True)
#%qtconsole --style vim
# dates
StartA = '2009-01-01'
StartB = '2009-03-05'
StartC = '2009-02-20'
FinishA='2009-02-28'
FinishB='2009-04-15'
FinishC='2009-05-30'
LabelDateA='2009-01-25'
LabelDateB='2009-03-20'
LabelDateC='2009-04-01'
# sample data
df = [dict(Task="Task A", Start=StartA, Finish=FinishA),
dict(Task="Task B", Start=StartB, Finish=FinishB),
dict(Task="Task C", Start=StartC, Finish=FinishC)]
# figure
fig = ff.create_gantt(df)
# add annotations
annots = [dict(x=LabelDateA,y=0,text="Task label A", showarrow=False, font=dict(color='white')),
dict(x=LabelDateB,y=1,text="Task label B", showarrow=False, font=dict(color='White')),
dict(x=LabelDateC,y=2,text="Task label C", showarrow=False, font=dict(color='White'))]
# plot figure
fig['layout']['annotations'] = annots
# Step 1 - adjust margins to make room for the text
fig.update_layout(margin=dict(t=150))
# Step 2 - add line
fig.add_shape(type='line',
x0=LabelDateB,
y0=0,
x1=LabelDateB,
y1=1,
line=dict(color='black', dash='dot'),
xref='x',
yref='paper'
)
# Step 3 - add text with xref set to x
# and yref set to 'paper' which will let you set
# text outside the plot itself by specifying y > 1
fig.add_annotation(dict(font=dict(color="black",size=12),
#x=x_loc,
x=LabelDateB,
y=1.06,
showarrow=False,
text='<b>Today</b>',
textangle=0,
xref="x",
yref="paper"
))
fig.update_layout(
title_text="Academic year 2019/2020"
)
fig.show()
How to draw a line or add a text outside of the plot area in R?
The xpd parameter controls where you can draw. Check the current value with par()$xpd and then try setting par(xpd=NA).
From the par help:
‘xpd’ A logical value or ‘NA’. If ‘FALSE’, all plotting is
clipped to the plot region, if ‘TRUE’, all plotting is
clipped to the figure region, and if ‘NA’, all plotting is
clipped to the device region. See also ‘clip’.
How to put text outside python plots?
It's probably best to define the position in figure coordinates instead of data coordinates as you'd probably not want the text to change its position when changing the data.
Using figure coordinates can be done either by specifying the figure transform (fig.transFigure
)
plt.text(0.02, 0.5, textstr, fontsize=14, transform=plt.gcf().transFigure)
or by using the text
method of the figure instead of that of the axes.
plt.gcf().text(0.02, 0.5, textstr, fontsize=14)
In both cases the coordinates to place the text are in figure coordinates, where (0,0)
is the bottom left and (1,1)
is the top right of the figure.
At the end you still may want to provide some extra space for the text to fit next to the axes, using plt.subplots_adjust(left=0.3)
or so.
Annotate outside plot area once in ggplot with facets
You can put a single tag label on a graph using tag
in labs()
.
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point() +
facet_grid(.~cyl ) +
labs(tag = "XX") +
coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off")
This defaults to "top left", though, which may not be what you want. You can move it around with the theme element plot.tag.position
, either as coordinates (between 0 and 1 to be in plot space) or as a string like "topright"
.
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point() +
facet_grid(.~cyl ) +
labs(tag = "XX") +
coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off") +
theme(plot.tag.position = c(.01, .95))
Related Topics
Shiny Datatable in Landscape Orientation
How to Append R Data Frame into Existing Excel Without Overwriting
How to Apply Histogram on Dependent Data in R
Loop Linear Regression and Saving Coefficients
Extract First N Digits from a String
How to Use Different Font Sizes in Ggplot Facet Wrap Labels
How to Use Custom Cross Validation Folds with Xgboost
How to Split a Dataframe Column by The First Instance of a Character in Its Values
How to Create Dynamic Number of Observeevent in Shiny
How to Remove Certain Columns in Multiple Data Frames in R
Strange Behaviour Dropping Column from Data.Frame in R
Extracting "((Adj|Noun)+|((Adj|Noun)(Noun-Prep))(Adj|Noun))Noun" from Text (Justeson & Katz, 1995)
Robust Standard Errors for Mixed-Effects Models in Lme4 Package of R
Dynamically Formatting Individual Axis Labels in Ggplot2
How to Combine Repelling Labels and Shadow or Halo Text in Ggplot2