The problem is the y_h = 1 is not aligned properly with the y = 0.3 and so on, how do i fix this? Below i left a picture of the problem im facing and the code.
yaxis's not aligned
x = 2
y = np.array([0.3, 0.11, 0.43])
y_h = np.array([1, 2, 3])
fig, host = plt.subplots(figsize=(8, 5))
fig.subplots_adjust(right=0.75)
colormap = plt.get_cmap("gist_rainbow")
colors = [colormap(i) for i in np.linspace(0, 1, y.size)]
line = host.twinx()
#plot the lines the give them colors and labels
for i in range(y.size):
p = line.plot([x - x, x], [y_h[i], y[i]], color=colors[i], label="p"+str(i))
#append the line labels to a list
'''for i in range(y.size):
pis.append('p'+str(i))'''
host.set_xlim(0, x)
host.set_ylim(0, y_h.size)
line.set_ylim(0, max(y))
host.set_xlabel("Rev_Count")
host.set_ylabel("Value")
line.set_ylabel('Value_Header')
plt.show()
Related
I've been looking online for help but nothing that I have seen is helping me to add space between the xticks without losing any xtick labels on the x axis. Here is my code and the things that I have tried to get the figure below to the current layout. Is there an auto-adjust that works? "plt.tight_layout" should do that but doesn't seem to work for me. thank you for help here. And, the plt.suptitle is not centered above the month (February).
#CALC VARIABILITY AND PLOT BOXPLOTS for ea month
sitenames = df3.plant_name.unique().tolist()
months = ['JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER']
from datetime import datetime
monthn = datetime.now().month
newList = list()
for i in range(monthn-1):
newList.append(months[(i)%12])
print(newList)
for i, month in enumerate(newList,1):
#plt.figure()
#fig, ax = plt.subplots()
#ax = df3[df3['month']==i].boxplot(by='plant_name',column='Var',grid=False)
datey = datetime.today().strftime("%Y")
ax = df3[df3['month']==i].plot(kind='scatter',x='plant_name',y='Var',marker='.',s=5,grid=False)
stdp[stdp['month']==i].plot(kind='scatter', x = 'plant_name',
y='Var',color='k',marker='_',s=200,label = '1+Std', grid=False,ax=ax)
stdn[stdn['month']==i].plot(kind='scatter', x = 'plant_name',
y='Var',color='k',marker='_',s=200,label = '1-Std', grid=False,ax=ax)
stdp2[stdp2['month']==i].plot(kind='scatter', x = 'plant_name',
y='Var',color='k',marker='_',s=50,label = '2+Std',grid=False,ax=ax)
stdn2[stdn2['month']==i].plot(kind='scatter', x = 'plant_name',
y='Var',color='k',marker='_',s=50,label = '2-Std',grid=False,ax=ax)
medn[medn['month']==i].plot(kind='scatter', x = 'plant_name',
y='Var',color='g',marker='_',s=90,label = 'p50',grid=False,ax=ax)
df3c[df3c['month']==i].plot(kind='scatter', x = 'plant_name', y='Var',color='r',label =
datey,grid=False,ax=ax)
# Save the default tick positions, so we can reset them...
locs, labels = plt.xticks()
plt.xticks(rotation=90, ha='center')
plt.suptitle('1991-2020 ERA5 WIND PRODUCTION',y=1)
plt.title(months[i-1])
plt.xlabel('SITE')
plt.ylabel('VARIABILITY')
#plt.legend()
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5),prop={'size': 8})
plt.tick_params(axis='x', which='major', labelsize=10)
plt.tight_layout(rect=[0, 0, 2, 1])
plt.subplots_adjust(bottom=0.1)
Without "plot_tight_layout(rect[0, 0, 2, 1])"
And, with "plot_tight_layout(rect[0, 0, 2, 1])" included:
I've tried specifying in a few ways but have not been able to get this figure any bigger than what's shown.
category_names = ['Database', 'Frontend', 'QA', 'ML', 'Fullstack']
labels = list(final_df.index)
data = np.array(final_df.iloc[:, 1:])
data_cum = data.cumsum(axis=1)
category_colors = plt.get_cmap('RdYlGn')(np.linspace(0, 1000, data.shape[1]))
fig, ax = plt.subplots(figsize=(100,75))
ax.invert_yaxis()
# ax.xaxis.set_visible(False)
ax.set_xlim(0, 200)
for i, (colname, color) in enumerate(zip(category_names, category_colors)):
widths = data[:, i]
starts = data_cum[:, i] - widths
ax.barh(labels, widths, left=starts, height=0.5,
label=colname, color=color)
xcenters = starts + widths / 2
r, g, b, _ = color
text_color = 'white' if r * g * b < 0.5 else 'darkgrey'
for y, (x, c) in enumerate(zip(xcenters, widths)):
ax.text(x, y, str(int(c)), ha='center', va='center',
color=text_color, fontsize=15)
If I make the figsize any bigger, the kernel dies and I've tried adjusting height and np.linspace params, as well as trying to set size with fig.set_size_inches. Any ideas on what's going on here?
Why is the following behaviour happening to my colorbars.. and how do I get it to behave "normal"?
x_array = np.random.rand(5, 15, 10)
x_array = np.array([np.random.randint(1,20) * x for x in x_array])
minmax_array = [-2, 2]
f = plt.figure()
ag = axes_grid.ImageGrid(f, rect=(1, 1, 0), nrows_ncols=(1,5), cbar_mode='each',
cbar_pad=0.05, axes_pad=0.5)
for j in range(5):
x_temp = x_array[j, :, :]
im = ag[j].imshow(x_temp)
ag.cbar_axes[j].colorbar(im)
ag.cbar_axes[j].set_yticks(minmax_array)
The result of this is shown below
As you can see, since I supply colorbar range outside of the values of the arrays.. I get this weird scaling of the colorbar.
But why cant it scale
The reason for this is because vmin and vmax have not been set in imshow. If we execute the following code
x_array = np.random.rand(5, 15, 10)
x_array = np.array([np.random.randint(1,20) * x for x in x_array])
minmax_array = [-2, 2]
f = plt.figure()
ag = axes_grid.ImageGrid(f, rect=(1, 1, 0), nrows_ncols=(1,5), cbar_mode='each',
cbar_pad=0.05, axes_pad=0.5)
for j in range(5):
x_temp = x_array[j, :, :]
im = ag[j].imshow(x_temp, vmin=minmax_array)
ag.cbar_axes[j].colorbar(im)
ag.cbar_axes[j].set_yticks(minmax_array)
Note that "if vmin is a length2 sequence, interpret it as (vmin, vmax) which is used to support setp"
I am adding a second x-axis to my plot like this:
ax2 = ax.twiny()
offset = 0, -25
new_axisline = ax2.get_grid_helper().new_fixed_axis
ax2.axis["bottom"] = new_axisline(loc="bottom", axes=ax2, offset=offset)
ax2.axis["top"].set_visible(False)
ax2.set_xticks(xticks)
ax2.xaxis.set_major_formatter(ticker.NullFormatter())
ax2.xaxis.set_minor_locator(ticker.FixedLocator(xticks))
ax2.xaxis.set_minor_formatter(ticker.FixedFormatter(xticks_labels))
the problem is I don't know how I can rotate the labels from there.
Also: If I add ticks to my first axis:
plt.xticks(xticks1, xticks1_labels, rotation='vertical')
the rotation argument gets ignored and I don't understand why either.
I have tried
ax2.set_xticklabels(ax2.xaxis.get_minorticklabels(), rotation=45)
but it also has no effect.
Any help would be appreciated.
You can take a look at the complete plotting logic below:
def event_plot(event_list, labels=None, figsize=(16, 9), padding=0.85, grid=False, title=None, colors=None):
fig = plt.figure(figsize=figsize)
ax = SubplotHost(fig, 111)
# ax = fig.add_subplot(111)
fig.add_subplot(ax)
ax.grid(grid)
if title is not None:
ax.set_title(title)
max_end = 0
for i, events in enumerate(event_list):
for event in events:
start = event[0]
end = event[1]
max_end = max(max_end, end)
y = (i, i + padding)
c = 'red' if colors is None else colors[i]
plt.fill_between([start, end], y[0], y2=y[1], color=c, alpha=0.35, linewidth=0.0)
plt.legend(['Recording data available for channel'], loc='upper center')
if labels is not None:
labels_ids = np.asarray(range(len(labels))) + 1
labels_y = labels_ids - 0.5 - (1 - padding) / 2.
plt.yticks(labels_y, labels)
for y in labels_y:
plt.axhline(y, alpha=0.125, color='k', linestyle='--')
return ax, fig
def plot_case_windows(all_records, case_windows, filename_title, filename=None):
channel_event_list = list()
labels = list()
for group_name, group in all_records.channel_groups.items():
[(labels.append(x[0]), channel_event_list.append(x[1])) for x in group.items()]
recording_time = all_records.end - all_records.start
title = 'File: {:s}, recording time: {:d} sec'.format(os.path.basename(filename_title), int(recording_time))
ax1, fig = event_plot(channel_event_list, title=title, labels=labels)
xticksmax = 0
xticksmin = float('Inf')
xticks1 = list()
xticks1_labels = list()
xticks2 = list()
xticks2_labels = list()
for case_win in case_windows:
xticks1.append(int(case_win.start + (case_win.end - case_win.start)/2.))
xticks2.append(case_win.start)
xticksmax = max(xticksmax, case_win.end)
xticksmin = min(xticksmin, case_win.start)
xticks1_labels.append(case_win.name)
xticks2_labels.append(str(case_win.start) + ' s')
plt.axvline(x=case_win.start, color='k', linestyle='--')
plt.axvline(x=case_win.end, color='k', linestyle='--')
xticks2 = (np.asarray(xticks2) - xticksmin) / (xticksmax - xticksmin)
plt.xlim([xticksmin, xticksmax])
ax1.set_xticks(xticks1)
ax1.xaxis.set_major_formatter(ticker.NullFormatter())
ax1.xaxis.set_minor_locator(ticker.FixedLocator(xticks1))
ax1.xaxis.set_minor_formatter(ticker.FixedFormatter(xticks1_labels))
ax2 = ax1.twiny()
offset = 0, -20
new_axisline = ax2.get_grid_helper().new_fixed_axis
ax2.axis["bottom"] = new_axisline(loc="bottom", axes=ax2, offset=offset)
ax2.axis["top"].set_visible(False)
ax2.set_xticks(xticks2)
ax2.xaxis.set_major_formatter(ticker.NullFormatter())
ax2.xaxis.set_minor_locator(ticker.FixedLocator(xticks2))
ax2.xaxis.set_minor_formatter(ticker.FixedFormatter(xticks2_labels))
plt.setp(ax2.xaxis.get_minorticklabels(), rotation=45)
# ax2.set_xticklabels(ax1.xaxis.get_minorticklabels(), rotation=45)
#plt.show()
plt.tight_layout()
if filename:
plt.savefig(filename)
I'm trying to do a scatterplot and heatmap in the same plot.
The scatterplot is as follows:
examples, targets = zip(*list(blue_data()))
examples2, targets2 = zip(*list(red_data()))
plt.plot(np.array(examples), np.array(targets), 'o', color = 'b')
plt.plot(np.array(examples2), np.array(targets2), 'o', color = 'r')
The above works just fine. I also want to do a heatmap. It works just fine, if I do it in a separate subplot. However, I want to try to do both on the same plot, sharing the same axes and am unsure how to do it. This is the code for the heatmap:
x = np.linspace(lower_x, upper_x, 100)
y = np.linspace(lower_y, upper_y, 100)
X, Y = np.meshgrid(x, y)
Z = np.zeros((x.size,y.size))
for ii in range(len(x)):
for jj in range(len(y)):
X_ = X[ii,jj];
Y_ = Y[ii,jj];
Z[ii,jj] = some_function(X_,Y_)
cmap = mpl.colors.ListedColormap(['r', 'b'])
bounds = [-100,0,100]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
plt.imshow(Z,cmap= cmap, norm = norm, extent = [-lower_x,upper_x,-lower_y,upper_y], origin = 'lower');
How can I combine the two plots so that they appear on the same plot with aligned axes?