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

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:

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:

Scaling and Labelling KDE plots [duplicate]

This question already has answers here:
Matplotlib Legends not working
(4 answers)
How to set the y-axis limit
(8 answers)
Closed 1 year ago.
I plotted PDF using kdeplot. I am having a tough time to scale and label the plots.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
error = np.array([1,2,2,3,4,4,5])
error2 = np.array([3,3,4,4,4,6])
sns.kdeplot(error, color='blue',label='error')
sns.kdeplot(error2, color='red',label='error2')
plt.show()
I want the blue curve to be labelled as 'error' and red curve to be labelled as 'error2'.
Also, I want to scale the y-axis. It should be in the range of 0 to 1 with 0.1 interval. How can I achieve this?
Thanks in advance
To add a legend, just add
plt.legend()
above plt.show(). To set the limit of the axis, use
ax = plt.gca() # get current axis
ax.set_ylim([0, 1])
To set the ticks accordingly, you can use
ax.set_yticks(np.arange(0, 1.1, 0.1))
(All above plt.show())

How to iteratively plot lines with colors from a sequential color function [duplicate]

This question already has answers here:
use matplotlib color map for color cycle
(5 answers)
Closed 1 year ago.
I would like to plot 3 figures in python. I plotted it manually.
The code is:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1, 1)
Semesters=np.arange(1,7,1)
y1=np.arange(10,16,1)
y2=np.arange(20,26,1)
y3=np.arange(51,57,1)
plt.plot(Semesters, y1,label="To Reach 120",linewidth=2)
plt.plot(Semesters, y2,label="To Reach 100",linewidth=2)
plt.plot(Semesters, y3,label="To Reach 80",linewidth=2)
ax.set_xticks(Semesters)
plt.legend(bbox_to_anchor=(0.85, .3), loc=2, borderaxespad=0.)
I want to use for loop and rainbow function (or any other sequential color function) for its color considering legends. Any help is appreciated.
Here is one solution for you.
Explanation: Create your y-data in a list (y_list here) and store your labels (labels here). Then just loop over the lists to plot one at a time using a for loop as you asked.
To define the colors using a color map, rainbow for instance, create a list of colors using the number of lines (plots) you have (3 in the example below). Then just assign those colors within the for loop and you have your desired plot.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
fig, ax = plt.subplots(1, 1)
Semesters=np.arange(1,7,1)
y_list = [np.arange(10,16,1), np.arange(20,26,1), np.arange(51,57,1)]
labels = ["To Reach 120", "To Reach 100", "To Reach 80"]
# Define the colors to be used using rainbow map (or any other sequential map)
colors = cm.rainbow(np.linspace(0, 1, len(y_list)))
# Plot the lines using a for loop
for i in range(len(y_list)):
plt.plot(Semesters, y_list[i], label=labels[i], linewidth=2., color=colors[i])
ax.set_xticks(Semesters)
plt.legend(bbox_to_anchor=(0.85, .3), loc=2, borderaxespad=0.)

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()

Why are the heatmap color values appearing as thin rectangular strips instead of squares? [duplicate]

This question already exists:
pandas/seaborn - how to improve the appearance of this heatmap?
Closed 6 years ago.
How can I improve the appearance of this heatmap? Why are the color values appearing as thin rectangular strips (with all that white space in between) instead of squares or is this what normally happens depending on the data file? This is not what the heatmap is supposed to look like.
Data
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)
np.random.seed(sum(map(ord, "distributions")))
data = pd.read_csv('dvAng_heatmap.dat',sep='\s',engine='python')
data2 = pd.pivot_table(data.round(2),values='k',index='g',columns='h')
mask = np.isnan(data2)
sns.set(style="white")
xtics = 20
ytics = 10
cmap = "jet"
vmin = None
vmax = None
ax = sns.heatmap(data2, xticklabels=xtics, yticklabels=ytics, mask=mask, linewidths=0, cbar=True, robust=False,cmap=cmap, vmin=vmin, vmax=vmax)
ax.invert_yaxis()
plt.title('Heatmap')
plt.xlabel('angle')
plt.ylabel('separation')
plt.savefig('Heatmap.png', transparent=True)
sns.plt.show()
Read the documentation. All you have to do is add the square=True keyword. By default, this option set to False.
Under the hood, seaborn is calling matplotlib.pyplot.imshow and using the square keyword just sets Axes.set_aspect('equal'). If using square=True has too extreme of an effect, you can try setting the aspect manually: ax.set_aspect(num) where num is a number describing the height:width ratio of resulting rectangles.

Categories

Resources