So I have the following code:
## BAR PLOTS
#expected value vs probability of choosing option1
fig, ax = plt.subplots(1, 2, dpi=320)
data.plot(kind='bar', y='value_1', ax=ax[0], color ='red')
data.plot(kind='bar', y='p_1', ax=ax[1], color ='blue')
#ax.set_xlabel("Trials")
#ax.set_ylabel("Value 1 / P_1")
#plt.xticks(np.arange(0, len('value_1')+1, 5), np.arange(0, len('value_1')+1, 5) )
#ticks = range(0, 500, 5)
#labels = ticks
#plt.xticks(ticks, labels)
plt.xticks(np.arange(0, len(data.value_1)+1, 5), np.arange(0, len(data.value_1)+1, 5) )
#ax.legend(["Value 1, P_1"])
plt.title('Bar plots Practice , Expected Vs. Probability')
fig.savefig("figure.pdf")
plt.show()
See now The graph is fine, and showing everything that I would want it to show; however, as you can see in this picture below, there is a problem with reading the x-axis / having the tickers spaced out correctly. I've tried to fix it several different ways but have not been able to make it look clean like an excel graph.
Try increasing the figure size, plt.figure(figsize = (15,15))
Related
I've two frames as you can see on the picture. I want to automatically center this two figures and put in a photo. But I failed in the first part. My code is:
fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows = 2, ncols = 2)
# Axes 1
ax1 = plt.subplot2grid((3, 3), (0, 0))
#ax1.set_title[['[0,0]']
# Axes 2
ax2 = plt.subplot2grid((3, 3), (0, 2))
I've two other plots, but they don't have to be considered. How to I center this according the whole fig? I couldn't find anything on the matplot site.
Thanks.
Assuming that you don't want the ratio of the displayed length of x- and y-axes of the subplots in the first row of the figure to change, we can use plt.subplot to get the expected result by creating a finer resolution of row by having more columns accessible to plot a particular subplot:
import matplotlib.pyplot as plt
fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows = 2, ncols = 2)
# Creates a 3 * 13 grid on the figure
ax1 = plt.subplot(3, 13, (4, 6))
ax2 = plt.subplot(3, 13, (8, 10))
plt.show()
This gives:
I want to compare two distributions- one from real data- just plot histogram of cases and function of date and the other from predict model- plot the distribution.
I have two codes, one for each distribution:
only KDE without hist-
ax=sns.displot(PLT2['DATE'],kind="kde")
plt.xticks(rotation=90, fontsize=10)
ax.set(xlim=(datetime.date(2013, 1, 1), datetime.date(2013, 12, 31)))
histogram from real data-
ax=sns.displot(df['DATE'].sort_values(),stat="density")
plt.xticks(rotation=90, fontsize=10)
plt.show()
I want to show those two on the same plot. I tried this code but in return 2 different plots:
ax1=sns.displot(df_2013['DATE'].sort_values(),stat="density")
ax2=sns.displot(PLT2['DATE'],kind="kde")
plt.xticks(rotation=90, fontsize=10)
ax1.set(xlim=(datetime.date(2013, 1, 1), datetime.date(2013, 12, 31)))
ax2.set(xlim=(datetime.date(2013, 1, 1), datetime.date(2013, 12, 31)))
plt.show()
thanks for helping
You need to define the figure first and add subplots to it.
with sns.axes_style("whitegrid"):
fig = plt.figure(figsize=(15,10))
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.plot(df1['Column1'])
ax2.plot(df2['Column1'])
This way you can also plot on the same axis and overlay your plots if you want to. Or you can make plots align under each other in seperate subplots.
Here is an example of superimposed distplots that might be useful to you.
fig = plt.figure(figsize=(7.5,7.5))
ax1 = fig.add_subplot(211)
sns.distplot(Fnormal,ax = ax1, label="Normal Distribution from Filter");
sns.distplot(FilteredReturns, ax =ax1, label="Filtered Returns");
ax1.set_title('Comparison of Filtered Returns and Normal Distribution')
ax1.legend()
My goal is to add a thick set of grid marks over the existing ones I have created using pcolor (see code below). There would be one thick grid line for every N (5 for instance) thinner grid lines. The grid lines I want to add could be analogous to major tick marks while the existing grid lines could be analogous to minor tick marks.
My code:
Z = np.random.rand(25, 25)
fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')
gs = gridspec.GridSpec(2, 3, width_ratios=[1,1,0.1])
ax1 = plt.subplot(gs[0,1])
plt1 = ax1.pcolor(Z, cmap=plt.cm.Blues, edgecolors='k', linewidths=1)
cbax = plt.subplot(gs[0,2])
cb = Colorbar(ax=cbax, mappable = plt1)
Output image:
random data with grid lines
Doctored image with red lines showing major grid I want: same data with doctored red grid lines
Does anyone have a good solution or work around for this?
I was able to resolve my issue by digging around in the matplotlib.pyplot.grid documentation.
Here is my updated code:
Z = np.random.rand(25, 25)
fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')
gs = gridspec.GridSpec(2, 3, width_ratios=[1,1,0.1])
ax1 = plt.subplot(gs[0,1])
plt1 = ax1.pcolor(Z, cmap=plt.cm.Blues, edgecolors='k', linewidths=1)
ax1.xaxis.set_major_locator(MultipleLocator(5))
ax1.yaxis.set_major_locator(MultipleLocator(5))
ax1.grid(b=True, which='major', color='r', linestyle='-')
cbax = plt.subplot(gs[0,2])
cb = Colorbar(ax=cbax, mappable = plt1)
Output figure:
random data with major and minor grid lines
I'm attempting to plot two bar charts using matplotlib.pyplot.subplots. I've created subplots within a function, but when I output the subplots they are too long in height and not long enough in width.
Here's the function that I wrote:
def corr_bar(data1, data2, method='pearson'):
# Basic configuration.
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(7, 7))
ax1, ax2 = axes
corr_matrix1 = data1.corr(method=method)
corr_matrix2 = data2.corr(method=method)
cmap = cm.get_cmap('coolwarm')
major_ticks = np.arange(0, 1.1, 0.1)
minor_ticks = np.arange(0, 1.1, 0.05)
# Values for plotting.
x1 = corr_matrix1['price'].sort_values(ascending=False).index
x2 = corr_matrix2['price'].sort_values(ascending=False).index
values1 = corr_matrix1['price'].sort_values(ascending=False).values
values2 = corr_matrix2['price'].sort_values(ascending=False).values
im1 = ax1.bar(x1, values1, color=cmap(values1))
im2 = ax2.bar(x2, values2, color=cmap(values2))
# Formatting for plot 1.
ax1.set_yticks(major_ticks)
ax1.set_yticks(minor_ticks, minor=True)
plt.setp(ax1.get_xticklabels(), rotation=45, ha='right', rotation_mode='anchor')
ax1.grid(which='both')
ax1.grid(which='minor', alpha=0.4)
ax1.grid(which='major', alpha=0.7)
ax1.xaxis.grid(False)
# Formatting for plot 2.
ax2.set_yticks(major_ticks)
ax2.set_yticks(minor_ticks, minor=True)
plt.setp(ax2.get_xticklabels(), rotation=45, ha='right', rotation_mode='anchor')
ax2.grid(which='both')
ax2.grid(which='minor', alpha=0.4)
ax2.grid(which='major', alpha=0.7)
ax2.xaxis.grid(False)
fig.tight_layout()
plt.show()
This function (when run with two Pandas DataFrames) outputs an image like the following:
I purposely captured the blank right side of the image as well in an attempt to better depict my predicament. What I want is for the bar charts to be appropriately sized in height and width as to take up the entire space, rather than be elongated and pushed to the left.
I've tried to use the ax.set(aspect='equal') method but it "scrunches up" the bar chart. Would anybody happen to know what I could do to solve this issue?
Thank you.
When you define figsize=(7,7) you are setting the size of the entire figure and not the subplots. So your entire figure must be a square in this case. You should change it to figsize=(14,7) or use a number larger than 14 to get a little bit of extra space.
I have a graph that plots a series circles, however, because of the axes they aren't coming out as circles, but as ovals, as you can see in the image below. I know this is a reoccurring problem, and there are many questions like this... However I can't find anything that helps me! I've tried putting in fig = plt.figure(0, figsize=(14.5, 1.75)) which does slightly help, but maybe ax.set_aspect() however, using scalars for this hasn't helped much either!
For this plot, the line marked *** is not there
my code is as follows:
fig = plt.figure(0)
ax = fig.add_subplot(111)
ax.set_aspect(???)#*** not sure if this should be here or not
plt.axis([-5, 20, -1, 1])
circle1 = plt.Circle((-1,0.25), radius=0.2, color='c')
circle2= plt.Circle((4,-0.5), radius=0.5, color='m')
plt.gcf().gca().add_artist(circle1)
plt.gcf().gca().add_artist(circle2)
You can set the aspect to be equal but you will also need to choose similar sizes for both axis as follows:
from matplotlib import pyplot as plt
fig = plt.figure(0)
ax = fig.add_subplot(111)
ax.set_aspect('equal')
plt.axis([-5, 5, -5, 5])
circle1 = plt.Circle((-1, 0.25), radius=0.2, color='c')
circle2 = plt.Circle((4, -0.5), radius=0.5, color='m')
ax.add_artist(circle1)
ax.add_artist(circle2)
plt.show()
Which would display as follows: