How to find the centre of a 3D scatter plot? - python

I have been trying to plot the center of a 3D scatter plot and I am facing an issue determining the value for the z-value. I want the z axis value that puts the centre on the scatter plot. How to find the centre of a 3D scatter plot?
Here is what I have tried.
import xlrd
import numpy as np
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# axes = [5, 5, 5]
# Create Data
# data = np.ones(axes, dtype=np.bool)
df=pd.read_csv('wr.csv')
df=df.sample(frac=1)
# print(df.head())
fig = plt.figure()
#---------------1st plt-------------------------
ax = fig.add_subplot(projection='3d')
ax.scatter(df.index, df['volatile acidity'], np.ones(df.shape[0]), s=5,color='red')
ax.scatter(np.mean(df.index),np.mean(df['volatile acidity']),1,color='black',s=200)
Fig1
Now I wanted to try the same thing with a different approach and let the z-axis value change dynamically according to the scatter plot.
import xlrd
import numpy as np
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# axes = [5, 5, 5]
# Create Data
# data = np.ones(axes, dtype=np.bool)
df=pd.read_csv('wr.csv')
df=df.sample(frac=1)
# print(df.head())
fig = plt.figure()
#---------------1st plt-------------------------
ax = fig.add_subplot(projection='3d')
#ax.scatter(df.index, df['volatile acidity'], np.ones(df.shape[0]), s=5,color='red')
#ax.scatter(np.mean(df.index),np.mean(df['volatile acidity']),1,color='black',s=200)
ax.scatter(df.index, df['volatile acidity'], np.square(df['volatile acidity']), s=5,color='black')
ax.scatter(np.mean(df.index),np.mean(df['volatile acidity']),1,color='orange',s=20)
Here is the image for reference.
Fig2

Related

How animation scatter plot with Matplotlib can be done with not superimposed data?

I want to do an animated scatter plot with one only pair of x,y data for each frame.
The code I wrote creates an animated scatter plot but the old dots appear in the plot, that means that new dots are added on the plot, keeping the old ones.
For the code below I want a dot per frame like a moving dot on x axis and not adding one more value.
I tried with plt.clf() but then all data disappear.
%matplotlib notebook
from bokeh.plotting import figure, output_file, show
import pandas
import numpy as np
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation, PillowWriter
import matplotlib.pyplot as plt
writer = PillowWriter(fps=10)
list_x=[1,2,3,4,5,6,7,8,9]
list_y=[5,5,5,5,5,5,5,5,5]
def plot(listax, listay):
plt.scatter(listax, listay, c='blue', alpha=0.5)
plt.show()
fig2 = plt.figure()
plt.xlim([0, 10])
plt.ylim([0, 10])
with writer.saving(fig2, "plotvideo.gif", 100):
for i in range(0, len(list_x)):
x_value = list_x[i]
y_value = list_y[i]
writer.grab_frame()
plot(x_value, y_value)
Use the .remove() method on the point objects to remove them from the figure.
I would try this:
from bokeh.plotting import figure, output_file, show
import pandas
import numpy as np
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation, PillowWriter
import matplotlib.pyplot as plt
import time
writer = PillowWriter(fps=10)
list_x=[1,2,3,4,5,6,7,8,9]
list_y=[5,5,5,5,5,5,5,5,5]
points = []
def plot(listax, listay, j):
points.append(plt.scatter(listax[j], listay[j], c='blue', alpha=0.5))
if len(points) == 2:
points[0].remove()
points.pop(0)
plt.show(block=False)
fig2 = plt.figure()
plt.xlim([0, 10])
plt.ylim([0, 10])
with writer.saving(fig2, "plotvideo.gif", 100):
for i in range(0, len(list_x)):
x_value = list_x
y_value = list_y
writer.grab_frame()
print(points)
plot(x_value, y_value, i)
See this link for a better explanation (albeit with a different implementation):
How to remove points from a plot?

How to remove the white shade/color from the heatmap using sns.kdeplot()? I just want the red color

from mplsoccer.pitch import Pitch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import kde
from scipy.ndimage import gaussian_filter
from copy import copy
np.random.seed(19680801)
plt.style.use('dark_background')
fields = ['id', 'minute', 'result', 'X1', 'Y','xG','h_a','situation','season',
'shotType','X']
df=pd.read_csv('shots.csv', skipinitialspace=True, usecols=fields)
fig, ax = pitch.draw()
sns.kdeplot(df.Y, df.X,shade=True, ax=ax, cmap='Reds',
shade_lowest=False,levels=20,kernel='gau',gridsize=50,
bw='scott',cut=0,cbar=True,)
ax.set_xlim(ax.get_xlim()[::-1]) # invert the axis
ax.yaxis.tick_right()
plt.axis('off')
plt.show()
The values df.X & df.Y lie between (0,1).
I want the red part only. In matplotlib I used vmin argument eliminate the white part. What can be done here?
Edit: On second thoughts, the White region would be eliminated if the colormap starts from 12 in the fig attached. So the colormap starts from red and ends on dark red. That's what I would like.
I would use this approach to pick colours out of your colormap:
from matplotlib import cm
from matplotlib.colors import ListedColormap
# select 42 colours from the "Reds" cmap
red_selection = cm.get_cmap("Reds", 42)
# select half of the colours, closest to Red and assign to a new colormap
red_cmap = ListedColormap(red_selection(range(42))[21:, :])
from mplsoccer.pitch import Pitch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import kde
from scipy.ndimage import gaussian_filter
from copy import copy
np.random.seed(19680801)
plt.style.use('dark_background')
fields = ['id', 'minute', 'result', 'X1', 'Y','xG','h_a','situation','season',
'shotType','X']
df=pd.read_csv('shots.csv', skipinitialspace=True, usecols=fields)
fig, ax = pitch.draw()
sns.kdeplot(df.Y, df.X,shade=True, ax=ax, cmap=red_cmap,
shade_lowest=False,levels=20,kernel='gau',gridsize=50,
bw='scott',cut=0,cbar=True,)
ax.set_xlim(ax.get_xlim()[::-1]) # invert the axis
ax.yaxis.tick_right()
plt.axis('off')
plt.show()

How to create specific plots using Pandas and then store them as PNG files?

So I am trying to create histograms for each specific variable in my dataset and then save it as a PNG file.
My code is as follows:
import pandas as pd
import matplotlib.pyplot as plt
x=combined_databook.groupby('x_1').hist()
x.figure.savefig("x.png")
I keep getting "AttributeError: 'Series' object has no attribute 'figure'"
Use matplotlib to create a figure and axis objects, then tell pandas which axes to plot on using the ax argument. Finally, use matplotlib (or the fig) to save the figure.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Sample Data (3 groups, normally distributed)
df = pd.DataFrame({'gp': np.random.choice(list('abc'), 1000),
'data': np.random.normal(0, 1, 1000)})
fig, ax = plt.subplots()
df.groupby('gp').hist(ax=ax, ec='k', grid=False, bins=20, alpha=0.5)
fig.savefig('your_fig.png', dpi=200)
your_fig.png
Instead of using *.hist() I would use matplotlib.pyplot.hist().
Example :
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
y =[10, 20,30,40,100,200,300,400,1000,2000]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = Values')
plt.title('my plot')
ax.legend()
plt.show()
fig.savefig('tada.png')

seaborn histogram to have different color bins

A simple histogram by seaborn. I want to highlight the top 3 bins with a different color. Here shows a matplotlib way, but not a seaborn way.
Is there any ways to show different colored bins in seaborn?
Thank you.
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data = np.random.normal(loc = 6, size=100)
ax = sns.distplot(data, bins = 20)
plt.xlim(0, 10)
plt.show()
If there are no other plots on the same ax, you could loop through all its patches, find the 3 highest and color them:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
data = np.random.normal(loc = 6, size=500)
ax = sns.distplot(data, bins = 20)
heights = [p.get_height() for p in ax.patches]
third_highest = sorted(heights)[-3]
for p in ax.patches:
if p.get_height() >= third_highest:
p.set_color('crimson')
plt.xlim(0, 10)
plt.show()

How to generate a colorbar for manually colored plots in matplotlib?

Suppose I need to control line colors myself for some reason, for example:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
for i in np.linspace(0, 1, 100):
plt.plot([i,i+1,i+2], color=mpl.cm.viridis(i))
How to generate a colorbar for such a plot?
You would need to create a colorbar without any reference axes. This can be done with the matplotlib.colorbar.ColorbarBase class. See also this example from the gallery.
To use this, you need to create a new axis in the plot, where the colorbar should sit in; one way of doing this is to use make_axes_locatable.
Here is a complete example.
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
for i in np.linspace(0, 1, 9):
plt.plot([i,i+1,i+2], color=mpl.cm.viridis(i))
divider = make_axes_locatable(plt.gca())
ax_cb = divider.new_horizontal(size="5%", pad=0.05)
cb1 = mpl.colorbar.ColorbarBase(ax_cb, cmap=mpl.cm.viridis, orientation='vertical')
plt.gcf().add_axes(ax_cb)
plt.show()

Categories