I'm making some plots with mathplotlib, the y axis is in log scale. I want to have both major and minor grids on both X and Y axis. The first plot comes out perfect (meaning that my code works), while in the second plot the y-minorgrid is suppressed (I assume for ease of visualisation reasons). I want to overcome this and impose the presence of y-minorgrid, even if the resulting plot looks less clear.
Any suggestion?
Current code is
fig, axes = plt.subplots(1, 1, figsize=[18, 10])
axes.plot(DF['value'])
axes.set_title('whatever')
axes.set_ylabel('Pressure [mbar]')
axes.set_xlabel('time [s]')
axes.set_yscale('log')
axes.set_ylim([1E-8, 10000])
axes.grid(b=True, which='minor', color='orange', linestyle=':')
axes.grid(b=True, which='major')
axes.minorticks_on()
take a look at this post below that may be helpful to your scenario. Good luck!
matplotlib: Setting both major and minor ticks forces same x and y scale
Related
So I have been trying to generate a heatmap in python such that the Matplotlib graph that is generated does not have any white margins in both x and y axes and the graph's scaling must be 1:1 with respect to the x and y axes units. I have tried many things but the best I have been able to achieve so far is able to remove the x axis white margins but not the y one. Here's an example:
This is what I am getting:
This is what I want:
Here's the code through which I am generating the graph:
plt.style.use('classic')
plt.axis('equal')
plt.pcolormesh(x_mesh,y_mesh,intensity)
plt.plot(x,y,linestyle="None",marker='.',markerfacecolor='white')
#plt.colorbar()
#plt.axis('off')
plt.margins(x=0,y=0)
plt.ylim([0,254])
plt.xlim([0,538])
plt.savefig('plottest.png', dpi=144, bbox_inches='tight', pad_inches=0)
plt.show()
Any help would be highly appreciated! Thanks!
Try changing plt.axis('equal') to plt.axis('scaled'). As the documentation says:
equal: ... Explicit data limits may not be respected in this case.
I am trying to make my plots a bit more readable and have come across a feature where the axes are automatically scaled by factors of tens (so instead of the y axis reading 0.00000005, 0.00000007, 0.00000009, it reads 0.5,0.7,0.9 and then says 1e-7 at the top of the axis). However some of my plots don't scale the axes automatically, and I would like to get advise of how to do that manually.
I have found threads on manually setting the tick marks, however I haven't been able to find threads on scaling only.
I can't imbed pictures but here is a link to a picture of what I would like to do: Ideal y axis and here's link to a picture of what I want to avoid: Current y axis.
I'm using seaborn formatting and matplotlib for plots and my code looks like this:
plt.plot(x_j_n,y_j_n, label='Scanning i negativ retning', color='grey', ls='dashed')
plt.plot(x_j_p,y_j_p, label='Scanning i positiv retning', color='black', ls='dashed')
plt.errorbar(x_j_n,y_j_n, yerr=std_j_n, fmt='o', color='black', mfc='white', label = 'Usikkerhed')
plt.errorbar(x_j_p,y_j_p, yerr=std_j_p, fmt='o', color='grey', mfc='white', label = 'Usikkerhed')
plt.ylabel('Målt spænding i volt (V)')
plt.xlabel('Påtrykt felt i tesla (T)')
plt.legend()
plt.show;
Set the y axis to scientific:
plt.gca().yaxis.get_major_formatter().set_scientific(True)
For example:
x = [1100000,2200000,3300000]
y = [1100000,2200000,3300000]
plt.plot(x,y)
plt.gca().xaxis.get_major_formatter().set_scientific(False)
plt.gca().yaxis.get_major_formatter().set_scientific(True)
plt.show()
will give:
I am trying to display the weighted frequency in the y-axis of a seaborn.distplot() graph, but it keeps displaying the density (which is the default in distplot())
I read the documentation and also many similar questions here in Stack.
The common answer is to set norm_hist=False and also to assign the weights in a bumpy array as in a standard histogram. However, it keeps showing the density and not the probability/frequency of each bin.
My code is
plt.figure(figsize=(10, 4))
plt.xlim(-0.145,0.145)
plt.axvline(0, color='grey')
data = df['col1']
x = np.random.normal(data.mean(), scale=data.std(), size=(100000))
normal_dist =sns.distplot(x, hist=False,color="red",label="Gaussian")
data_viz = sns.distplot(data,color="blue", bins=31,label="data", norm_hist=False)
# I also tried adding the weights inside the argument
#hist_kws={'weights': np.ones(len(data))/len(data)})
plt.legend(bbox_to_anchor=(1, 1), loc=1)
And I keep receiving this output:
Does anyone have an idea of what could be the problem here?
Thanks!
[EDIT]: The problem is that the y-axis is showing the kdevalues and not those from the weighted histogram. If I set kde=False then I can display the frequency in the y-axis. However, I still want to keep the kde, so I am not considering that option.
Keeping the kde and the frequency/count in one y-axis in one plot will not work because they have different scales. So it might be better to create a plot with 2 axis with each showing the kde and histogram separately.
From documentation norm_hist If True, the histogram height shows a density rather than a count. **This is implied if a KDE or fitted density is plotted**.
versusnja in https://github.com/mwaskom/seaborn/issues/479 has a workaround:
# Plot hist without kde.
# Create another Y axis.
# Plot kde without hist on the second Y axis.
# Remove Y ticks from the second axis.
first_ax = sns.distplot(data, kde=False)
second_ax = ax.twinx()
sns.distplot(data, ax=second_ax, kde=True, hist=False)
second_ax.set_yticks([])
If you need this just for visualization it should be good enough.
I am trying to have a non linear x - axis in Python using matplotlib and haven't found any functions or hack arounds to this problem.
This is how our graph looks at this point of time and I want to convert it to something like this. (Look at the difference in x axes of both graphs)
The code I have as of now is:
plt.axis([0, 100, 0, 1])
plt.plot(onecsma_x, onecsma_y, label='1-CSMA')
plt.plot(slotted_aloha_x,slotted_aloha_y, label ='Slotted Aloha')
plt.plot(pure_aloha_x,pure_aloha_y, label ='Pure Aloha')
plt.plot(npcsma_x, npcsma_y, label ='Non persisten CSMA')
plt.plot(pcsma_x, pcsma_y, label ='P persistent CSMA')
plt.legend(loc='upper right')
plt.show()
For log x-axis use semilogx instead of plot.
Also you could limit the x-axis maybe after using semilogx (but before show) with:
plt.xlim(0, 10**2)
Sorry for giving an image however I think it is the best way to show my problem.
As you can see all of the bin width are different, from my understanding it shows range of rent_hours. I am not sure why different figure have different bin width even though I didn't set any.
My code looks is as follows:
figure, axes = plt.subplots(nrows=4, ncols=3)
figure.set_size_inches(18,14)
plt.subplots_adjust(hspace=0.5)
for ax, age_g in zip(axes.ravel(), age_cat):
group = total_usage_df.loc[(total_usage_df.age_group == age_g) & (total_usage_df.day_of_week <= 4)]
sns.distplot(group.rent_hour, ax=ax, kde=False)
ax.set(title=age_g)
ax.set_xlim([0, 24])
figure.suptitle("Weekday usage pattern", size=25);
additional question:
Seaborn : How to get the count in y axis for distplot using PairGrid for here it says that kde=False makes y-axis count however http://seaborn.pydata.org/generated/seaborn.distplot.html in the doc, it uses kde=False and still seems to show something else. How can I set y-axis to show count?
I've tried
sns.distplot(group.rent_hour, ax=ax, norm_hist=True) and it still seems to give something else rather than count.
sns.distplot(group.rent_hour, ax=ax, kde=False) gives me count however I don't know why it is giving me count.
Answer 1:
From the documentation:
norm_hist : bool, optional
If True, the histogram height shows a density rather than a count.
This is implied if a KDE or fitted density is plotted.
So you need to take into account your bin width as well, i.e. compute the area under the curve and not just the sum of the bin heights.
Answer 2:
# Plotting hist without kde
ax = sns.distplot(your_data, kde=False)
# Creating another Y axis
second_ax = ax.twinx()
#Plotting kde without hist on the second Y axis
sns.distplot(your_data, ax=second_ax, kde=True, hist=False)
#Removing Y ticks from the second axis
second_ax.set_yticks([])