Ось X временной шкалы графика Seaborn: как отобразить значение каждого столбца - PullRequest
1 голос
/ 26 мая 2020

Как отображать значение каждого столбца, когда ваш рисунок (столбец) имеет временной ряд в виде оси X:

У меня есть фрейм данных df_final_seaborn:

enter image description here

    Covid-19 Madagascar Isan'ny olona
Daty        
2020-05-24  Sitrana isan'andro  4
2020-05-24  Maty                0
2020-05-25  Marary isan'andro   15
2020-05-25  Sitrana isan'andro  5
2020-05-25  Maty                0

и построить полосу со следующим кодом:

sns.set(rc={'figure.figsize':(30,15)},palette=['#F70A0A','#2A930C','#930C85'], font_scale=1.7)
# pour les axes 
ax = sns.barplot(x=df_final_seaborn.index,y='Isan\'ny olona',data=df_final_seaborn,hue='Covid-19 Madagascar')
sns.set_style("darkgrid" , {"ytick.major.size": 10 , "ytick.minor.size": 2 , 'grid.linestyle': '--'})
plt.xticks(rotation=90)
plt.xlabel('Daty', fontsize = 20)
plt.ylabel('Isan\'ny olona', fontsize = 20)
plt.minorticks_on()
plt.legend(loc='upper left')
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2 , axis='y')
ax.xaxis.set_major_formatter(plt.FixedFormatter(df_sea.index.to_series().dt.strftime("%Y-%m-%d")))
plt.show()

результат:

enter image description here

Моя проблема в том, как отображать каждое значение бара:

Я следил за той же проблемой здесь введите описание ссылки здесь , добавив код ниже

for index , row in df_final_seaborn.iterrows():
   ax.text(row.name,row['Isan\'ny olona'], round(row['Isan\'ny olona'],0), color='black', ha="center")


plt.show()

Out : TypeError: float() argument must be a string or a number, not 'Timestamp'

для информации, когда я помещаю

for index , row in df_final_seaborn.iterrows():
    print(index)
    print(row)

, результат будет:

enter image description here

Другое решение - через matplotlib, как здесь: введите здесь описание ссылки

добавив это перед: plt.show ()

for i , v in enumerate (df_final_seaborn):
       plt.text(df_final_seaborn.iloc[i], v + 0.01, str(v))

out:

TypeError                                 Traceback (most recent call last)
<ipython-input-127-717d236faadf> in <module>
     12 ax.xaxis.set_major_formatter(plt.FixedFormatter(df_sea.index.to_series().dt.strftime("%Y-%m-%d")))
     13 for i , v in enumerate (df_final_seaborn):
---> 14        plt.text(df_final_seaborn.iloc[i], v + 0.01, str(v))
     15 #      print(i)
     16 #      print(v)

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

есть идея?

1 Ответ

2 голосов
/ 26 мая 2020

Вы не должны перебирать фрейм данных, поскольку соответствие между строками и столбцами не гарантируется. Вместо этого перебирайте столбцы:

sns.set(rc={'figure.figsize':(30,15)},palette=['#F70A0A','#2A930C','#930C85'], font_scale=1.7)
# pour les axes 
ax = sns.barplot(x=df_final_seaborn.index,y='Isan\'ny olona',data=df_final_seaborn,hue='Covid-19 Madagascar')
sns.set_style("darkgrid" , {"ytick.major.size": 10 , "ytick.minor.size": 2 , 'grid.linestyle': '--'})
plt.xticks(rotation=90)

for patch in ax.patches:
    x, width, height = patch.get_x(), patch.get_width(), patch.get_height()
    color = patch.get_facecolor()

    # ignore 0 and nan values
    if height is None or height==0: continue

    ax.text( x+width/2, height+0.1, f'{height}',ha='center',color=color)

Вывод:

enter image description here

...