python: changing the size of ax.matshow in matplotlib [duplicate] - python

This question already has answers here:
Matplotlib: Getting subplots to fill figure
(3 answers)
Closed 5 years ago.
I was trying to plot a heatmap using matplotlib similar to the heatmap of plotly. I am able to get the output by the size of the matshow figure is very small. The following is the figure
Is it possible to get the following figure:
The following is my code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
z = []
for _ in range(7):
new_row = []
for __ in range(180):
new_row.append(np.random.poisson())
z.append(list(new_row))
df1 = pd.DataFrame(np.array(z), columns=range(len(z[0])))
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(111)
cax = ax.matshow(df1, interpolation='nearest', cmap='coolwarm')
fig.colorbar(cax)
ax.set_xticklabels([''] + list(df1.columns))
ax.set_yticklabels([''] + list(df1.index))
plt.show()
Kindly help.

You may want to use
ax.matshow(... , aspect="auto")
to remove the restriction of equal aspect on imshow or matshow.

Related

Is it possible to remove the empty side of the scatter plot matrix? [duplicate]

This question already has answers here:
Plot lower triangle in a seaborn Pairgrid
(2 answers)
Closed 5 days ago.
I would like to remove the 6 empty boxes on the top right side of the plot(pls see the figure marked in red). I tried few different arguments and it didn't work.
Here is the code I used.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Example dataset
iris = sns.load_dataset("iris")
# Create PairGrid object with subplots
g = sns.PairGrid(iris, height=1.5, aspect=1.2)
# Create scatter plots on the lower side
g.map_lower(sns.scatterplot)
# Add regression line
g.map_lower(sns.regplot)
# Add histograms
g.map_diag(sns.histplot, kde=True)
# Then include correlation values for each scatter plot.
for i, j in zip(*plt.np.triu_indices_from(g.axes, k=1)):
corr_coef = plt.np.corrcoef(iris.iloc[:, i], iris.iloc[:, j])[0][1]
g.axes[j, i].annotate(f"R = {corr_coef:.2f}", xy=(.1, .9), xycoords=g.axes[j, i].transAxes)
plt.show()
You can use corner argument like this:
g = sns.PairGrid(iris, height=1.5, aspect=1.2, corner=True)
Result:

Shaded area either side of mean on line graph - matplotlib, seaborn - Python [duplicate]

This question already has answers here:
Why am I getting a line shadow in a seaborn line plot?
(2 answers)
Seaborn lineplot using median instead of mean
(2 answers)
Closed 10 months ago.
`def comparison_visuals(df_new):
matplotlib.rc_file_defaults()
ax1 = sns.set_style(style=None, rc=None )
fig, ax1 = plt.subplots(figsize=(12,6))
sns.lineplot(data = df_new, x='Date', y=
(df_new['Transfer_fee'])/1000000, marker='o', sort = False,
ax=ax1)
ax2 = ax1.twinx()
from matplotlib.ticker import FormatStrFormatter
ax1.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
sns.lineplot(data = df_new, x='Date', y='Inflation', alpha=0.5,
ax=ax2)
from matplotlib.ticker import FormatStrFormatter
ax2.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
comparison_visuals(df_new)'
(Edited to paste code above)
Can anyone tell me what the shaded area represents on my line graph (see screenshot)? The middle line represents the mean. I haven't specifically added it. I would like to know first what it is and secondly how to remove it (I might chose to keep it if I find out what it represents and it adds value to my visualisation).
Any related answers I've come across don't del with this directly. Thansk in advance.
Screenshot of line graph

plot more vertical density plots in one graph [duplicate]

This question already has an answer here:
Half violin plot in matplotlib
(1 answer)
Closed 2 years ago.
I would like to obtain a graph similar to the one I drew:
In the x axis the date of the collected data, and in the y axis the associated densities.
I wrote these few lines:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
from datetime import datetime
df = pd.DataFrame(np.random.rand(7, 100), columns=['y']*100)
df.index = pd.date_range(datetime.today(), periods=7).tolist()
sns.kdeplot(data=df, y='y', fill=True, alpha=.5, linewidth=0)
plt.show()
but of course it doesn't work. How can I modify the code to get what I imagined?
Can be done easily using statsmodels.graphics.boxplots.violinplot
from statsmodels.graphics.boxplots import violinplot
fig, ax = plt.subplots()
violinplot(data=df.values, ax=ax, labels=df.index.strftime('%Y-%m-%d'), side='right', show_boxplot=False)
fig.autofmt_xdate()

python matplotlib histogram specify different colours for different bars [duplicate]

This question already has answers here:
Matplotlib histogram with multiple legend entries
(2 answers)
Closed 4 years ago.
I want to colour different bars in a histogram based on which bin they belong to. e.g. in the below example, I want the first 3 bars to be blue, the next 2 to be red, and the rest black (the actual bars and colour is determined by other parts of the code).
I can change the colour of all the bars using the color option, but I would like to be able to give a list of colours that are used.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(1000)
plt.hist(data,color = 'r')
One way may be similar to approach in other answer:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
data = np.random.rand(1000)
N, bins, patches = ax.hist(data, edgecolor='white', linewidth=1)
for i in range(0,3):
patches[i].set_facecolor('b')
for i in range(3,5):
patches[i].set_facecolor('r')
for i in range(5, len(patches)):
patches[i].set_facecolor('black')
plt.show()
Result:

Seaborn - remove spacing from DataFrame histogram [duplicate]

This question already has answers here:
How can I change the x axis in matplotlib so there is no white space?
(2 answers)
Closed 5 years ago.
I am trying to generate a histogram from a DataFrame with seaborn enabled via the DataFrame.hist method, but I keep finding extra space added to either side of the histogram itself, as seen by the red arrows in the below picture:
How can I remove these spaces? Code to reproduce this graph is as follows:
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from random import seed, choice
seed(0)
df = pd.DataFrame([choice(range(250)) for _ in range(100)], columns=['Values'])
bins = np.arange(0, 260, 10)
df['Values'].hist(bins=bins)
plt.tight_layout()
plt.show()
plt.tight_layout() only has an effect for the "outer margins" of your plot (tick marks, ax labels etc.).
By default matplotlib's hist leaves an inner margin around the hist bar-plot. To disable you can do this:
ax = df['Values'].hist(bins=bins)
ax.margins(x=0)
plt.show()

Categories

Resources