Show Element Values in Barplot

Show element values in barplot

You just need to make sure that ylim is large enough such that none of the text will be placed outside of the plot area, and then you need the positions of the middle of bars and make sure to place the text there.

set.seed(123)
origin <-c(2, 3.5, 5, 7.9, 8.8, 12.3)
x<-sample(origin, 100, replace=T)
b<-barplot(table(x),ylim=c(0,22))
text(x=b, y= table(x)+1, labels=as.character(table(x)))

Sample Image

How to display the value of the bar on each bar with pyplot.barh()

Update: there's a built in method for this now! Scroll down a couple answers to "New in matplotlib 3.4.0".

If you can't upgrade that far, it doesn't take much code. Add:

for i, v in enumerate(y):
ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')

result:

Sample Image

The y-values v are both the x-location and the string values for ax.text, and conveniently the barplot has a metric of 1 for each bar, so the enumeration i is the y-location.

how to show values on top of bar plot

Simply add

for i, v in enumerate(y):
plt.text(xlocs[i] - 0.25, v + 0.01, str(v))

before plt.show(). You can adjust the centralization or height of the text by changing the (-0.25) and (0.01) values, respectively.

New plot

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5))

Sample Image

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year),
transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr...
# Data <- group_by(Data,Year) %>%
# mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
geom_bar(aes(fill = Category), stat="identity") +
geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

Show values on top of bars in a barChart

Check updated jsfiddle

.renderlet(function(chart){

var barsData = [];
var bars = chart.selectAll('.bar').each(function(d) { barsData.push(d); });

//Remove old values (if found)
d3.select(bars[0][0].parentNode).select('#inline-labels').remove();
//Create group for labels
var gLabels = d3.select(bars[0][0].parentNode).append('g').attr('id','inline-labels');

for (var i = bars[0].length - 1; i >= 0; i--) {

var b = bars[0][i];
//Only create label if bar height is tall enough
if (+b.getAttribute('height') < 18) continue;

gLabels
.append("text")
.text(barsData[i].data.value)
.attr('x', +b.getAttribute('x') + (b.getAttribute('width')/2) )
.attr('y', +b.getAttribute('y') + 15)
.attr('text-anchor', 'middle')
.attr('fill', 'white');
}

})

If you don't want the labels visible when the bars redraw (for example when bars change after user filters/clicks other chart) you can move the check of old values from de renderlet to the to a preRedraw
listener.

.on("preRedraw", function(chart){

//Remove old values (if found)
chart.select('#inline-labels').remove();

})


Alternative

D3-ish way

Demo jsfiddle

.renderlet(function (chart) {

//Check if labels exist
var gLabels = chart.select(".labels");
if (gLabels.empty()){
gLabels = chart.select(".chart-body").append('g').classed('labels', true);
}

var gLabelsData = gLabels.selectAll("text").data(chart.selectAll(".bar")[0]);

gLabelsData.exit().remove(); //Remove unused elements

gLabelsData.enter().append("text") //Add new elements

gLabelsData
.attr('text-anchor', 'middle')
.attr('fill', 'white')
.text(function(d){
return d3.select(d).data()[0].data.value
})
.attr('x', function(d){
return +d.getAttribute('x') + (d.getAttribute('width')/2);
})
.attr('y', function(d){ return +d.getAttribute('y') + 15; })
.attr('style', function(d){
if (+d.getAttribute('height') < 18) return "display:none";
});

})

How do I display Y values above the bars in a matplotlib barchart?

using ax.patches you can achieve it.

This will do:

for p in ax.patches:
ax.annotate(str(round(p.get_height(),2)), (p.get_x() * 1.005, p.get_height() * 1.005),color='green')

Try:

sample data:

    1q1         1q2         1q3         1q4
Cust / Month
AA 62264.65 103189.45 94989.70 86212.37
AB 3330.47 0.00 0.00 0.00
AC 36580.00 36113.10 37527.84 32241.18
AD 36803.13 0.00 0.00 0.00
AE 44200.66 0.00 0.00 0.00
AF 12971.52 13697.76 13257.60 11931.84

Sample Code:

customer_count = [38.00, 30.00, 30.00, 20.00]

ax = res.T.plot(width=0.8, kind='bar',y=['Quarter Total'],figsize=(10,5))
for rect, value in zip(ax.patches, customer_count):
if value != 0:
h = rect.get_height() /2.
w = rect.get_width() /2.
x, y = rect.get_xy()
ax.text(x+w, y+h,value, horizontalalignment='center', verticalalignment='center', color='white',rotation=0)

for p in ax.patches:
ax.annotate(str(round(p.get_height(),2)), (p.get_x() * 1.005, p.get_height() * 1.005),color='green')

plt.title('expediture data Quarter Wise')

Sample Image




df:

    a   b   c   d
a1 66 92 98 17
a2 83 57 86 97
a3 96 47 73 32


ax = df.T.plot(width=0.8, kind='bar',y=df.columns,figsize=(10,5))
for p in ax.patches:
ax.annotate(str(round(p.get_height(),2)), (p.get_x() * 1.005, p.get_height() * 1.005),color='green')

ax.axes.get_yaxis().set_ticks([])

Sample Image

How to make bar plot of a list in Python

I believe you want something like this:

ax = sns.barplot(x=np.arange(len(lii)), y=lii)
ax.bar_label(ax.containers[0])
plt.axis('off')
plt.show()

Bar plot



Related Topics



Leave a reply



Submit