how to put text at the top of a 3D bar graph

2.6k Views Asked by At

I need to plot a 3D bar graph for my college project ,the bar graph is getting plotted but I want text to be displayed on each bar graph showing the values of its z-axis.

This is code snippet that shows for 2D graph: source code link

#!/usr/bin/env python
# a bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
menStd =   (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)

womenMeans = (25, 32, 34, 20, 25)
womenStd =   (3, 5, 2, 3, 3)
rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)

# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.show()

code for 3D bar graph is source code for 3d bar-graph

In the 2D version the autolabel function use get_height(), get_x() and get_width() to calculate the height dynamically which in not supported in 3D version it gives:

  • patch3d error for function not found

Is there any workaround to display text as in 2D graph.

2

There are 2 best solutions below

0
spfrnd On BEST ANSWER

You can extract the bar coordinates directly from the data and use matplotlib.pyplot.text, as pointed out by igavriil. For the example you provided that would look like this:

# Note that z and y-axis are swapped in the plot.
for x,y in zip(xs,ys):
    ax.text(x,z,y,'%2.2f'%y, horizontalalignment='left', verticalalignment='bottom')
0
Sayed Zainul Abideen On

Thanks igavriil that link helped and also thanks hr tur tur

I didn't got that parameter '%2.2f'%y how it works, there might be more cleaner way to plot this but I ploted it like this:

    def autolabel():
    """ attach some text labels"""
    for i in range(0, n):
        ax.text(int(x[i])+1, y[i]-2, z[i]+0.05, str(y[i])[0:4],     color='#660066', backgroundcolor= '#c187e1', weight= 'bold', rotation='vertical', fontsize=10, horizontalalignment='left', verticalalignment='bottom')      

Link:

DropBox link