I'm trying to plot a 2d histogram. The histogram is basically a galaxy and I have the points of each luminous point. I have plotted the histogram but it's not properly normalized, as the values of the colorbar should go from 0 to 1. How can I fix this?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import kde
fig, axes = plt.subplots(ncols=2, nrows=1, figsize=(20, 8))
data1 = pd.read_csv('mydata.txt', sep='\s+', header=None)
az1 = data1[0]
el1 = data1[1]
nbins = 250
hist1 = axes[0].hist2d(az1, el1, bins=nbins, cmap='magma', density=True)
fig.colorbar(hist1[3], ax = axes)
I tried with the function hist2Dbut I didn't find a way to normalized the result with it. So what I suggest is using the hitrogram from the numpy modul: np.nistogram2d where you can extract the result and then normalized the output before display it.
Here an example with random numbers:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import kde
fig, axes = plt.subplots(ncols=2, nrows=1, figsize=(20, 8))
# data1 = pd.read_csv('mydata.txt', sep='\s+', header=None)
N=10000
az1 = np.random.random(N)
el1 = np.random.random(N)
nbins = 250
hist1 = axes[0].hist2d(az1, el1, bins=nbins, cmap='magma', density=True)
fig.colorbar(hist1[3], ax = axes)
H, xedges, yedges = np.histogram2d(el1, az1, bins=(nbins, nbins),density=True )
# H_normalized = H/float(az1.shape[0]) # the integral over the histogrm is 1
H_normalized = H/H.max((0,1)) # the max value of the histogrm is 1
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
im = axes[1].imshow(H_normalized, extent=extent, cmap='magma', interpolation='none',origin ='lower')
fig.colorbar(im, ax=axes[1])
plt.show()
Related
I need plotting the circular histogram in matplotlib!
They should look like .
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np; np.random.seed(1)
r = np.ones(100)*0.9
phi = np.random.rand(100)*2.*np.pi
hist, xedges, yedges = np.histogram2d(r, phi, bins=25, range=[[0, 1.2], [0,2*np.pi*26./25]])
R,Phi = np.meshgrid(xedges[:-1], yedges[:-1])
X = R*np.cos(Phi)
Y = -R*np.sin(Phi)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X[(R < 0.75) | (R > 1)] = np.nan
ax.plot_surface(X,Y, hist.T, alpha=0.2)
ax.plot_wireframe(X,Y, hist.T)
plt.show()
Output:
I cannot get two different scales for the plot:
I don't know how to activate the scale of the secondary x axis.
"STK" and "Material" are supposed to be displayed at different scales.
How to display "Material" on it's own scale (0,max) like it was done automatically for "STK"?
I need it to be displayed like on the image below :
Here's the code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = [['MPP1',400,30],['MPP2',3500,700], ['MPP3',1900,3], ['MPP4',15000,56], ['MPP5',8500,306]]
df = pd.DataFrame(df)
df.columns =['MPP', 'STK', 'Material']
plt.rcdefaults()
fig, ax = plt.subplots(constrained_layout=True)
xdata = df.STK
x2data = df.Material
ydata = df.MPP
y_pos = np.arange(len(ydata))
ax.barh(y_pos, df.STK , label='STK per MPP')
ax.invert_yaxis()
ax.plot(x2data, ydata, label='Material per MPP', color='red')
ax.set_xlabel('STK')
ax.legend()
ax2 = ax.secondary_xaxis('top')
ax2.set_xlabel('Material')
ax2.set_xticks(df.Material)
ax2.set_xticklabels(df.Material)
ax2.set_xlabel(r"Material")
plt.show()
You should create the secondary axis with:
ax2 = ax.twiny()
and plot your data on it:
ax2.plot(x2data, ydata, label='Material per MPP', color='red')
Pay attention: ax2.plot, not ax.plot.
Complete Code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = [['MPP1',400,30],['MPP2',3500,700], ['MPP3',1900,3], ['MPP4',15000,56], ['MPP5',8500,306]]
df = pd.DataFrame(df)
df.columns =['MPP', 'STK', 'Material']
plt.rcdefaults()
fig, ax = plt.subplots(constrained_layout=True)
xdata = df.STK
x2data = df.Material
ydata = df.MPP
y_pos = np.arange(len(ydata))
ax.barh(y_pos, df.STK , label='STK per MPP')
ax.invert_yaxis()
ax.set_xlabel('STK')
leg = plt.legend()
ax2 = ax.twiny()
ax2.plot(x2data, ydata, label='Material per MPP', color='red')
ax2.set_xlabel('Material')
leg2 = plt.legend()
plt.legend(leg.get_patches()+leg2.get_lines(),
[text.get_text() for text in leg.get_texts()+leg2.get_texts()])
leg.remove()
plt.show()
I have the following script for generating a figure with two subplots: one line plot, and one bar plot.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
plt.close('all')
np.random.seed(42)
n = 1000
idx = pd.date_range(end='2020-02-27', periods=n)
df = pd.Series(np.random.randint(-5, 5, n),
index=idx)
curve = df.cumsum()
bars = df.resample('M').sum()
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
curve.plot(ax=ax1)
bars.plot(kind='bar', ax=ax2)
fig.set_tight_layout(True)
I would like to share the x axis between the two subplots, however the command ax2 = fig.add_subplot(212, sharex=ax1) will result in an empty graph for the line plot like the following figure.
Here is my version based on Matplotlib (without pandas api for plotting), may be it would be helpful.
I explicitly set the width of bars.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
%matplotlib inline
plt.close('all')
np.random.seed(42)
n = 1000
idx = pd.date_range(end='2020-02-27', periods=n)
df = pd.Series(np.random.randint(-5, 5, n), index=idx)
curve = df.cumsum()
bars = df.resample('M').sum()
#fig = plt.figure()
#ax1 = fig.add_subplot(211)
#ax2 = fig.add_subplot(212)
#curve.plot(ax=ax1)
#bars.plot(kind='bar', ax=ax2)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, gridspec_kw={'hspace': 0})
ax1.plot(curve.index, curve.values)
ax2.bar(bars.index, bars.values, width = (bars.index[0] - bars.index[1])/2)
fig.set_tight_layout(True)
_ = plt.xticks(bars.index, bars.index, rotation=90)
I would like to add a density plot to my histogram diagram. I know something about pdf function but I've got confused and other similar questions were not helpful.
from scipy.stats import *
from numpy import*
from matplotlib.pyplot import*
from random import*
nums = []
N = 100
for i in range(N):
a = randint(0,9)
nums.append(a)
bars= [0,1,2,3,4,5,6,7,8,9]
alpha, loc, beta=5, 100, 22
hist(nums,normed= True,bins = bars)
show()
I'm looking for something like this
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(41)
N = 100
x = np.random.randint(0, 9, N)
bins = np.arange(10)
kde = stats.gaussian_kde(x)
xx = np.linspace(0, 9, 1000)
fig, ax = plt.subplots(figsize=(8,6))
ax.hist(x, density=True, bins=bins, alpha=0.3)
ax.plot(xx, kde(xx))
Here's a solution using seaborn 0.11.1 and pandas 1.1.5:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
N = 100
nums = [np.random.randint(i-i, 9) for i in range(N)]
df = pd.DataFrame(nums, columns=["value"])
fig, ax1 = plt.subplots()
sns.kdeplot(data=df, x="value", ax=ax1)
ax1.set_xlim((df["value"].min(), df["value"].max()))
ax2 = ax1.twinx()
sns.histplot(data=df, x="value", discrete=True, ax=ax2)
Note how I use numpy to generate the random values because I need actual values, not generators. The discrete=True in the last line assures that the ticks are centered.
distplot from Seaborn offers histogram plot as well as distribution graph together:
sns.distplot(df)
I am currently have a nx3 matrix array. I want plot the three columns as three axis's.
How can I do that?
I have googled and people suggested using Matlab, but I am really having a hard time with understanding it. I also need it be a scatter plot.
Can someone teach me?
You can use matplotlib for this. matplotlib has a mplot3d module that will do exactly what you want.
import matplotlib.pyplot as plt
import random
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(projection='3d')
sequence_containing_x_vals = list(range(0, 100))
sequence_containing_y_vals = list(range(0, 100))
sequence_containing_z_vals = list(range(0, 100))
random.shuffle(sequence_containing_x_vals)
random.shuffle(sequence_containing_y_vals)
random.shuffle(sequence_containing_z_vals)
ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
plt.show()
The code above generates a figure like:
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
scatter plot
zdata = 15 * np.random.random(100)
xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
ax.scatter3D(xdata, ydata, zdata);
Colab notebook
Using plotly - Easiest and most functional and nice plots
import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
color='species')
fig.show()
https://plotly.com/python/3d-scatter-plots/