R graphics: Add labels to stacked bar chart - r

I am looking for a way to add labels, i.e. absolute values, into a stacked bar chart using the basic plot functions of R. The labels should be inside the stacked bars.
Thank you!

barplot will return the mid x position of the bars, so you could do
mydata <- matrix(c(10, 21, 22, 33, 45, 23, 22, 43, 33), nrow=3)
# b will contain the x midpoints of the bars
b <- barplot(mydata)
# This will write labels in the middle of the bars, horizontally and vertically
text(b, colMeans(mydata), c("Label1", "Label2", "Label3"))
# This will write labels in the middle of the middle block
text(b, mydata[1,]+mydata[2,]/2, c("LabelA", "LabelB", "LabelC"))
EDIT: re-reading your question, I think this is what you want (or maybe not, but I'll write it anyways :D)
# Find the top y position of each block
ypos <- apply(mydata, 2, cumsum)
# Move it downwards half the size of each block
ypos <- ypos - mydata/2
ypos <- t(ypos)
text(b, ypos, mydata)

How about the simple function text()?
You can simply add a string where ever you want, eg:
text (x = ..., y = ..., labels = c("foo bar 1000"))

Maybe you can use or inspect the barp function of the plotrix package

Related

How to draw histogram without the vertical lines in common between bars?

hist generates a histogram with the vertical boundaries of bars plots. If I don't want to draw the vertical boundaries that are common between adjacent bars, is there a way to do so?
If you want to retain the outline, it's pretty trivial to draw a polygon over the histogram:
set.seed(1)
h <- hist(rnorm(50))
polygon(rep(h$breaks, each = 2), c(0, rep(h$counts, each = 2), 0), col = "gray")
First some reproducible data:
set.seed(42)
x <- rnorm(100, 15, 4)
The border= argument is documented on the manual page for hist (?hist):
hist(x, border="lightgray")
No border.

Trouble adding color bar to Hive Plot in R

I'm working with a hive plot and want to know how to get a vertical color bar placed in the upper left quadrant of the plot, (not one that is off to the side of the plot). Problem is, whenever I run this code I'm not seeing anything pop up. I believe that could be because the methods I've been trying are all for normal plots, not hive plots.
colorplot.l <- seq(1,100,1)
require("grid")
require("HiveR")
test2 <- ranHiveData(nx = 2)
plotHive(test2, ch = 5, axLabs = c("axis 1", "axis 2"), rot = c(-90, 90),
axLab.pos = c(20, 20), axLab.gpar = gpar(col = "pink", fontsize = 14, lwd = 2),
arrow = c("radius units", 0, 20, 60, 25, 40))
colorbar.plot(0,100,colorplot.l, horizontal=FALSE)
Am I doing something wrong or is there another way specifically for a hive plot? Most packages I find don't work with this.
Any help or insight is appreciated.
Creating a viewport with the grid package you can add a color bar to your hive plot:
library(grid)
# A viewport on the upper left corner of the plot
legendViewport <- viewport(x=0.05, y=0.85, height=0.2, width=0.05)
pushViewport(legendViewport)
mypalette <- colorRampPalette(c("red","blue","green"))
# Render the color bar
grid.raster(mypalette(20),
width=unit(1,"npc"), height=unit(1,"npc"), int=FALSE)
Hope it can help you.

R: how to optimize the position of labeling in plot

Hi I guess that I have quite a rudimentary question here.
I have a plot like this
but as you could easily notice, some of the label could not be displayed (some are overlapped with the symbols, some are just out of the figure frame)
I noticed that there are some way to adjust the position of labels
text(tsne_out$Y[,1], tsne_out$Y[,2], labels=samplegrouptry, pos=1)
for example, I could specify the the value of "pos" (from 1 to 4). I guess they are good enough in most cases .But I wonder whether there are some better ways to do that.
Any suggestion, thanks!
Following the suggestion from
vas_u Through change the axis ranges as well as "pos", I could get better plot:
One way around the problem would be to enlarge the axes of the plot.
Your example approximately reproduced with dummy data:
x <- rnorm(16, mean = 0)
y <- rnorm(16, mean = 1)
# Initial scatterplot with text labels out of plot area:
plot(x, y, pch = 16)
text(x, y, labels = paste("Name", 1:16), pos = 1) # Some labels outside plot area
# Second plot with the X and Y axes gently expanded:
plot(x, y, pch = 16,
xlim = 1.1*range(x),
ylim = 1.1*range(y))
text(x, y, labels = paste("Name", 1:16), pos = 1) # Labels now fit inside!
I hope this helps.

R horizontal barplot with axis labels split between two axis

I have a horizontal barplot, with zero in the middle of the x-axis and would like the name for each bar to appear on the same side as the bar itself. The code I am using is:
abun<-data$av.slope
species<-data$Species
cols <- c("blue", "red")[(abun > 0)+1]
barplot(abun, main="Predicted change in abundance", horiz=TRUE,
xlim=c(-0.04,0.08), col=cols, names.arg=species, las=1, cex.names=0.6)
I have tried creating two separate axes and the names do appear on the desired side for each bar, but are not level with the appropriate bar. I will try and upload an image of the barplot, am still very new to R, apologies if I am missing something basic!
barplot1- names in correct position but all on one axis
barplot2- names on both sides of plot but not in line with appropriate bar
We can accomplish this using mtext:
generate data
Since you didn't include your data in the question I generated my own dummy data set. If you post a dput of your data, we could adapt this solution to your data.
set.seed(123)
df1 <- data.frame(x = rnorm(20),
y = LETTERS[1:20])
df1$colour <- ifelse(df1$x < 0, 'blue', 'red')
make plot
bp <- barplot(df1$x, col = df1$colour, horiz = T)
mtext(side = ifelse(df1$x < 0, 2, 4),
text = df1$y,
las = 1,
at = bp,
line = 1)

Initialize y-axis to be centered at 0

I'm generating some line plots that show percent error results. It would be nice if the y-axis was centered at 0 when the plots first load. I know I can manually set the bounds for the y-axis, but it would be tedious to have to set them manually for each figure.
Is there a way to set the figures to center at 0 along the y-axis?
Here's some code that may provide additional details -
from bokeh.plotting import figure, output_file, show
from bokeh.io import gridplot, hplot
# prepare some data
x = [1, 2, 3, 4, 5]
y1 = [-10, -9, 23, 4, -6]
y2 = [-15, -4, 26, 32, -45]
y3 = [-42, -20, -13, -34, -59]
y4 = [-23, -34, -32, -43, -53]
# output to static HTML file
output_file("lines.html", title="line plot example")
# create a new plot with a title and axis labels
p = figure(title="simple line example", x_axis_label='x', y_axis_label='y')
p.line(x, y1, line_width=2)
p.line(x, y2, line_width=2)
p2 = figure(title="simple line example", x_axis_label='x', y_axis_label='y')
p2.line(x, y3, line_width=2)
p2.line(x, y4, line_width=2)
p = hplot(p, p2)
show(p)
This generates two plots. The one on the right shows the problem I'm running into. Since all of the values are negative, the y-axis bounds are narrowed to approximately -10 to -60. I would like that chart to be bound at -60 to 60, so that it's aligned at 0.
Update:
I ended up just defining a function that will return the absolute max of the y values. Then, I am doing the following to set the limits:
axisLimit = getAxisRange(list1, list2) #get absolute max from the two lists
p.y_range = Range1d(start=-1*axisLimit, end=axisLimit)
There's no Bokeh method to center a plot around an axis like you describe. What did you did in your update seems like a good solution. You're always welcome to open an issue on the Bokeh project tracker at https://github.com/bokeh/bokeh/issues

Resources