1

I have such a dataframe df_new with index column name and column length:

name length 
U19 13
U17 14
U15 5
U13 10
U11 16
U9  17
U7  8

I want to get a barh plot with the displayed values of column length within the corresponding column.

I used a code which found here and modified a bit:

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

Here is my code:

import os
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()    
width = 0.75 # the width of the bars 
df_new.reset_index(inplace=True)
ind = df_new['name']  # the x locations for the groups
ax.barh(ind, df_new['Anzahl'],width, color="blue")
ax.set_yticks(ind+width/2)
ax.set_yticklabels(ind, minor=False)
plt.title('Title')
plt.xlabel('Anzahl')
plt.ylabel('Teams')
for i, v in enumerate(y):
    ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')

But get this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\ops\array_ops.py in _na_arithmetic_op(left, right, op, is_cmp)
    141     try:
--> 142         result = expressions.evaluate(op, left, right)
    143     except TypeError:

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\computation\expressions.py in evaluate(op, a, b, use_numexpr)
    234             # error: "None" not callable
--> 235             return _evaluate(op, op_str, a, b)  # type: ignore[misc]
    236     return _evaluate_standard(op, op_str, a, b)

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_numexpr(op, op_str, a, b)
    119     if result is None:
--> 120         result = _evaluate_standard(op, op_str, a, b)
    121 

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_standard(op, op_str, a, b)
     68     with np.errstate(all="ignore"):
---> 69         return op(a, b)
     70 

TypeError: can only concatenate str (not "float") to str

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-103-2825c3189564> in <module>
      4 ind = df_new['name']  # the x locations for the groups
      5 ax.barh(ind, df_new['Anzahl'],width, color="blue")
----> 6 ax.set_yticks(ind+width/2)
      7 ax.set_yticklabels(ind, minor=False)
      8 plt.title('Jugendteams')

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\ops\common.py in new_method(self, other)
     63         other = item_from_zerodim(other)
     64 
---> 65         return method(self, other)
     66 
     67     return new_method

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\arraylike.py in __add__(self, other)
     87     @unpack_zerodim_and_defer("__add__")
     88     def __add__(self, other):
---> 89         return self._arith_method(other, operator.add)
     90 
     91     @unpack_zerodim_and_defer("__radd__")

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\series.py in _arith_method(self, other, op)
   4996         lvalues = extract_array(self, extract_numpy=True)
   4997         rvalues = extract_array(other, extract_numpy=True)
-> 4998         result = ops.arithmetic_op(lvalues, rvalues, op)
   4999 
   5000         return self._construct_result(result, name=res_name)

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\ops\array_ops.py in arithmetic_op(left, right, op)
    187     else:
    188         with np.errstate(all="ignore"):
--> 189             res_values = _na_arithmetic_op(lvalues, rvalues, op)
    190 
    191     return res_values

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\ops\array_ops.py in _na_arithmetic_op(left, right, op, is_cmp)
    147             #  will handle complex numbers incorrectly, see GH#32047
    148             raise
--> 149         result = _masked_arith_op(left, right, op)
    150 
    151     if is_cmp and (is_scalar(result) or result is NotImplemented):

~\Downloads\WPy64-3920\python-3.9.2.amd64\lib\site-packages\pandas\core\ops\array_ops.py in _masked_arith_op(x, y, op)
    109         if mask.any():
    110             with np.errstate(all="ignore"):
--> 111                 result[mask] = op(xrav[mask], y)
    112 
    113     result, _ = maybe_upcast_putmask(result, ~mask, np.nan)

TypeError: can only concatenate str (not "float") to str

And this plot: pic

How should I modify my code?

StupidWolf
  • 45,075
  • 17
  • 40
  • 72
Tobitor
  • 1,388
  • 1
  • 23
  • 58
  • 1
    What is the y where you annotate the values? If it's your data, you'll need to change this. `for i, v in enumerate(df_new['length']):` – r-beginners May 16 '21 at 14:18

1 Answers1

2

I think the error is coming from this line because ind = df_new['name'] makes ind a string, and you cannot add a number to it:

ax.set_yticks(ind+width/2)

You used enumerate(y) to place the text, but y is not declared in the code, so it must be something floating in the environment.

If I set up the data frame like this:

df_new = pd.DataFrame({'length':[13,14,5,10,16,17,8]},
                   index = ['U19','U17','U15','U13','U11','U9','U7'])
df_new.index.name = "name"

And call the horizontal plot with pandas.DataFrame.plot.bar it works fine:

fig, ax = plt.subplots()    
df_new.plot.barh(width=0.75,ax=ax)
ax.set_title('Title')
ax.set_xlabel('Anzahl')
ax.set_ylabel('Teams')
ax.set_xlim([0,20])
for i, v in enumerate(df_new['length']):
    ax.text(x = v + 1, y = i + .1, s = str(v), color='blue', fontweight='bold')

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72