tvdsluijs
tvdsluijs

Reputation: 137

Make one y-axis label bold in matplotlib

Goodmorning,

Question, I've got this script that creates a horizontal bar chart (see image)

I would like to have one label in the y-axis bold "Nederland".

I've searched an tried a lot, but I really have no idea how I can do this.

I found this solution: Matplotlib - Changing the color of a single x-axis tick label But I could not get it to work.

Any hint to a solution would be great.

   def AVG_BarChart(self, data:dict=None, graph_file:str = None, datum:str=None, countries:dict=None, watermarktext:str="energieprijzenbot.nl", prijsper:str="kWh")->bool:
            plt.figure(figsize=(9, 6))
            plt.xlabel(f"Prijs per {prijsper}")
            plt.title(f"Gemiddelde {prijsper} inkoopprijs per land {datum}")

            colors = ["#FE8000", "#EFBD76", "#FFA52B", "#FF9D3C", "#FFF858", "#FCFFCB", "#07EEB2", "#FF4179","#E05B4B", "#E09336", "#DAB552", "#DBD9A6", "#87B49C", "#4B8A7E", "#A5DD96", "#E1F3C9", "#0095AD", "#00D5E5", "#82E9F0", "#C0ED42", "#FFE301", "#FFF352", "#FF85DA", "#FF69B3","#A15AC4", "#3F7539", "#B8CBAD", "#E1E2C2", "#F84040", "#9D1E29"]
            random.shuffle(colors)

            values = 2 ** np.random.randint(2, 10, len(data))
            max_value = values.max()

            labels = list(data.keys())
            values = list(data.values())

            height = 0.9
            plt.barh(y=labels, width=values, height=height, color=colors, align='center', alpha=0.8)

            ax = plt.gca()

            ax.xaxis.set_major_formatter('€ {x:n}')

            plt.bar_label(ax.containers[0], labels=[f'€ {x:n}' for x in ax.containers[0].datavalues], label_type="edge", padding=-50)

            ax.text(0.5, 0.5, watermarktext, transform=ax.transAxes,
                    fontsize=40, color='gray', alpha=0.3,
                    ha='center', va='center', rotation='30')

            for i, (label, value) in enumerate(zip(labels, values)):
                country_iso = self.get_key(val=label, my_dict=countries).lower()
                self.offset_image(x=value, y=i, flag=country_iso, bar_is_too_short=value < max_value / 10, ax=ax)

            plt.subplots_adjust(left=0.15)
            plt.savefig(graph_file, bbox_inches='tight', width = 0.4)

            return True

enter image description here

I tried looping thru the labels like this

   i = 0
   for w in ax.get_yticklabels():
      country = ax.get_yticklabels()[i].get_text()
      if country == "Nederland":
         ax.get_yticklabels()[i].set_color('red')
         ax.get_yticklabels()[i].set_fontweight('bold')
      i += 1

When debugging I actually get a country name back, but when running the script normal, all country labels are empty...

Upvotes: 1

Views: 2442

Answers (1)

tvdsluijs
tvdsluijs

Reputation: 137

So, I was close to the answer. But somehow I got back empty .get_text() string.

# ... some code

labels = list(data.keys())

# ... more code

ax.set_yticklabels(labels)

for lab in ax.get_yticklabels():
   if lab.get_text() == "Nederland":
      lab.set_fontweight('bold')

I just hope by setting the labels again, It does not mix up anything :-)

enter image description here

Upvotes: 3

Related Questions