Colour just the top border of geom_bar - r

A chart with a lot of bars looks very squished, for instance -
ggplot(data.frame(x = 1:1000, y = (rnorm(1000)), fill = sample(c('a','b','c'), 1000, replace = T)), aes(x, y, fill = fill)) + geom_bar(stat = 'identity')
I have a chart for a similar dataset which I feel I will be able to make more sense out of by just colouring the top border of the bar. I'm unable to achieve this. The closest I can do is incorporate a geom_step but this also adds vertical lines where the y value changes and this crowds the chart even more. geom_point sizes aren't necessarily synced with the separation on the x axis so they spill over to the side for small x values. The only sure shot solution I'm able to think of is to actually manipulate the data such that I'm able to draw geom_segments to do my work for me. Is there any other way
PS: I need to stick to this format for reasons.

You could use geom_errorbar() and set ymin= and ymax= to your y values. Then you can play with width= and size= to get the look you need.
ggplot(data.frame(x = 1:1000, y = (rnorm(1000)), fill = sample(c('a','b','c'), 1000, replace = T))) +
geom_errorbar(aes(x=x,ymin=y,ymax=y,color=fill),size=0.5,width=3)

Related

Bounding position for geom_text()

I am making several instances of a tilted bar chart. As the sizes of count and the differences in percent vary, part of one of the labels (count) is pushed outside the bar in some instances. I need the labels to be entirely inside the bar in all instances. If not repositioned to fit inside the bar, I need the labels to be centered as is.
The code is:
library(tidyverse)
library(ggplot2)
data <- tibble(type = c('Cat', 'Dog'),
group = c('Pets', 'Pets'),
count = c(10000, 990000),
percent = c(1, 99))
ggplot(data, aes(x = group, y = percent, fill = type)) +
geom_bar(stat = 'identity',
position = position_stack(reverse = TRUE)) +
coord_flip() +
geom_text(aes(label = count),
position = position_stack(vjust = 0.5,
reverse = TRUE))
Use hjust="inward":
ggplot(data, aes(x = group, y = percent, fill = type)) +
geom_bar(stat = 'identity', position = position_stack(reverse = TRUE)) +
coord_flip() +
geom_text(aes(label = count), hjust = "inward", position = position_stack(vjust = 0.5, reverse = TRUE))
One thing key to note here is that plots in ggplot are drawn differently depending on the graphics device resolution, width, and height settings. This is why plots look a bit different depending on the computer you use to plot them. If I take your default graph and save different aspect ratios, this becomes evident:
width=3, height=5
width=7, height=5
The aspect ratio and resolution change the plot. You can also see this for yourself within R studio by just resizing the plot viewer window.
With that being said, there are some options to adjust your plot to be less likely to clip text out of bounds:
Rotate your text or rotate your plot back to horizontal bars. For long text labels, they are going to work out better with horizontal bars anyway.
geom_text_repel from the ggrepel package. Direct replacement of geom_text puts your labels in the plot area, and you can use min.segment.length= to specify the minimum line length as well as force= and direction= to play with positioning. Again, works better if you flip back your chart.
Use the expand= argument applied to scale_y_continuous. Try adding scale_y_continuous(expand=c(0.25,0.25)) to your plot, for example. Note that since your coordinate system is flipped, you have to specify "y" to expand "x". This expands the plot area around the geoms.
Change the output width= and height= and resolution when exporting your plots. As indicated above, this is the simple solution.
There are probably other suggestions, but that's mine.

X axis labels tied to histogram bars instead of following separate rules

When using a histogram with x as a POSIXct value, I'm not sure how you're supposed to line the ticks up with the binsize of the graph.
Setting the tick size to the same as the binsize makes it line a bit off, but the offset adds onto each other until its no longer accurate.
bymonth <- ggplot() +
scale_x_datetime("", breaks = date_breaks("60 days"), labels = date_format("%m-%y")) +
...
lots of geom_rects for background colors
...
theme(legend.title = element_blank()) +
geom_histogram(data=dat, aes(x = iso, fill = name), binwidth = 30*24*60*60, position = 'dodge')
I tried using annotate() as well as experimenting with the spacing of the tick but I think my approach here might be wrong in its own accord
This leads to a graph looking something like this
Which is quite annoying

how to create shifted color scale ggplot

I have a continous variable that I would like to map to the color of my points.
However the distribution of the variable is shifted tot the right.
So I thought I could use the quantiles to set the breaks but this doesn't seem to be working.
I think I don't understand the subtleties between all of the different variants of scale_colour_gradient.
ggplot(df, aes(x = LibPl, y = IntStd, color = totSmpInt)) +
geom_point(position = "jitter", alpha = 0.5) +
scale_colour_gradientn(colours = brewer.pal(n = 4, "RdYlBu"),
breaks = c(qn[1], qn[2], qn[3], qn[4], qn[5]))
As you can see from the color legend in the plot it doesn't really seem like the quantiles were used as break points.
I have read a few other similar posts, and tried variants, but none are working
Any help is appreciated.
Thanks,

hHw to make width of bars equal in ggplot2 barplot?

I am trying to make the width of all bars in the following plot equal. Can anybody help me? is it possible? or is there any way to plot this data?
library(ggplot2)
dat <- data.frame(x = c('I','I','I','I','II','II'),
y = LETTERS[1:6],
z = abs(rnorm(6)))
ggplot(dat, aes(y,z))+
geom_bar(stat = "identity") +
facet_wrap(~x,scales="free")
I also tried using arguments size and width inside the geom_bar but its not working.
Really the problem is that each of the facet panels is being forced to be the same size and then the plot inside expands to fill all the available room. With facet_grid you can adjust the space for each facet panel (but you cannot seem to do this with facet_wrap). Try
ggplot(dat, aes(y,z))+
geom_bar(stat = "identity") +
facet_grid(~x,scales="free", space="free_x")
which gives me

In ggplot2, can borders of bars be changed on only one side? (color, thickness)

I know, 3D Barcharts are a sin. But i´m asked to do them and as a trade-off i suggested to only make a border with a slightly darker color than the bar´s on the top and the right side of the bar. Like that, the bars would have some kind of "shadow" (urgh) but at least you still would be able to compare them.
Is there any way to do this?
ggplot(diamonds, aes(clarity)) + geom_bar()
Another possibility, using two sets of geom_bar. The first set, the green ones, are made slightly higher and offset to the right. I borrow the data from #Didzis Elferts.
ggplot(data = df2) +
geom_bar(aes(x = as.numeric(clarity) + 0.1, y = V1 + 100),
width = 0.8, fill = "green", stat = "identity") +
geom_bar(aes(x = as.numeric(clarity), y = V1),
width = 0.8, stat = "identity") +
scale_x_continuous(name = "clarity",
breaks = as.numeric(df2$clarity),
labels = levels(df2$clarity))+
ylab("count")
As you already said - 3D barcharts are "bad". You can't do it directly in ggplot2 but here is a possible workaround for this.
First, make new data frame that contains levels of clarity and corresponding count for each level.
library(plyr)
df2<-ddply(diamonds,.(clarity),nrow)
Then in ggplot() call use new data frame and clarity as x values and V1 (counts) as y values and add geom_blank() - this will make x axis with levels we need. Then add geom_rect() to produce shading for bars - here xmin and xmax values are made as.numeric() from clarity and constant is added - for xmin constant should be less than half of bars width and xmax constant larger than half of bars width. ymin is 0 and ymax is V1 (counts) plus some constant. Finally add geom_bar(stat="identity") above this shadow to plot actually barplot.
ggplot(df2,aes(clarity,V1)) + geom_blank()+
geom_rect(aes(xmin=as.numeric(clarity)-0.38,
xmax=as.numeric(clarity)+.5,
ymin=0,
ymax=V1+250),fill="green")+
geom_bar(width=0.8,stat="identity")

Resources