I am trying to reproduce this:
using this code:
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom matplotlib.lines import Line2Dcolors = ["#CC5A43","#5375D4"]*3data = {"year": [2004, 2022, 2004, 2022, 2004, 2022],"countries" : ["Sweden", "Sweden", "Denmark", "Denmark", "Norway", "Norway"],"sites": [13,15,4,10,5,8]}df= pd.DataFrame(data)df['pct_change'] = df.groupby('countries', sort=True)['sites'].apply( lambda x: x.pct_change()).to_numpy()*-1df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()df = df.sort_values(['countries','year'], ascending=True ).reset_index(drop=True)df['diff'] = df.groupby(['countries'])['sites'].diff()df['diff'].fillna(df.sites, inplace=True)countries = df.countries.unique()code = df.ctry_code.unique()pct_change = df.pct_changex_coord = df.groupby('countries')['diff'].apply(lambda x: x.values) #convert the columns into numpy 2D arrayfig, ax = plt.subplots(figsize=(6,5), facecolor = "#FFFFFF")import matplotlib.cm# use a colormapcmap = plt.cm.RdBufor i, (color, x_c, country) in enumerate(zip(colors,x_coord, countries)): ax.broken_barh([x_c], (i-0.2,0.4),facecolors=cmap(0.7),alpha= 0.2)ax.scatter( df.sites, df.countries, marker="D", s=300, color = colors)ax.set(xlim=[0, 16], ylim=[-1, 3])ax.xaxis.set_ticks(np.arange(0,20,5),labels = [0,5,10,15])ax.tick_params(axis="x", which="major",length=0,labelsize=14,colors= '#C8C9C9')# Major ticks every 20, minor ticks every 5major_ticks = np.arange(0, 16, 1)ax.set_xticks(major_ticks)ax.grid(which='major', axis='x', linestyle='-', alpha=0.4, color = "#C8C9C9")ax.set_axisbelow(True)plt.yticks([])plt.box(False)#add legendlabels = ['2004','2022']colors = ["#5375D4","#CC5A43",]lines = [Line2D([0], [0], color=c, marker='D',linestyle='', markersize=12,) for c in colors]leg = ax.get_legend()plt.figlegend( lines,labels, labelcolor="#C8C9C9", bbox_to_anchor=(0.3, -0.1), loc="lower center", ncols = 2,frameon=False, fontsize= 12)Which produces this:
My question is, how do i do the gradient on the broken_barh plots? I have tried to do a cmap on facecolors, but no luck.
I have also tried using ax.barh and ax.plot but still stuck :(
