How to set title position inside graph in scatter plot? - python

MWE:
I would like the title position same as in the graph :
Here is my code :
import matplotlib.pyplot as plt
import numpy as np
import random
fig, ax = plt.subplots()
x = random.sample(range(256),200)
y = random.sample(range(256),200)
cor=np.corrcoef(x,y)
plt.scatter(x,y, color='b', s=5, marker=".")
#plt.scatter(x,y, label='skitscat', color='b', s=5, marker=".")
ax.set_xlim(0,300)
ax.set_ylim(0,300)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Correlation Coefficient: %f'%cor[0][1])
#plt.legend()
fig.savefig('plot.png', dpi=fig.dpi)
#plt.show()
But this gives :
How do I fix this title position?

assign two corresponded value to X and Y axis. notice! to have title inside graph, values should be in (0,1) interval. you can see a sample code here:
import matplotlib. pyplot as plt
A= [2,1,4,5]; B = [3,2,-2,1]
plt.scatter(A,B)
plt.title("title", x=0.9, y=0.9)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()

It will be unnecessarily complicated to move the title at some arbitrary position inside the axes.
Instead one would rather create a text at the desired position.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.random.randint(256,size=200)
y = np.random.randint(256,size=200)
cor=np.corrcoef(x,y)
ax.scatter(x,y, color='b', s=5, marker=".")
ax.set_xlim(0,300)
ax.set_ylim(0,300)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.text(0.9, 0.9, 'Correlation Coefficient: %f'%cor[0][1],
transform=ax.transAxes, ha="right")
plt.show()

Related

How to use np.arange() to create a 3D scatter plot

I'm trying to recreate a 3D scatter plot figure but I'm having a hard time with getting the range right on the y axis.
This is the figure that I am trying to emulate:
Here's my code for the np.arange():
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=[15,15])
z = 520 * np.random.random(100)
x = np.arange(0,20,0.2)
y = np.arange(0,20,0.2)
ax3 = fig.add_subplot(2,2,3, projection='3d')
ax3.set_xlabel('x', c='r', size=14)
ax3.set_ylabel('y', c='r', size=14)
ax3.set_zlabel('z', c='r', size=14)
ax3.scatter3D(x,y,z, c=z, cmap='jet')
ax3.view_init(25,45);
This is the output:
I'm not trying to make it look exactly the same with the angle but I need to get the axis plots correct.

Reduce the distance between the numbering on the axis and the ticks

How can I reduce the distance between the numbering of an axis and the ticks corresponding to them. I tried using pad=0 for the tick_params but it doesn't seem to work. Below is a reproducible (simplified) code of my issue (and the figure):
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
plt.rcParams["figure.figsize"] = (10,10)
fig = plt.figure()
ax = Axes3D(fig)
ax.set_xlabel("X" , fontsize=20)
ax.set_ylabel("Y", fontsize=20)
ax.set_zlabel("Z" , fontsize=20)
ax.view_init(azim=-20)
ax.tick_params(axis='x', which='major', pad=0)
x = np.arange(0,10,0.01)
y = np.ones(len(x))
z = np.sin(x)
plt.plot(x,y,z)
Changing the values of pad seem to not have any effect. Note: I need the plot in that specific orientation (azim=-20). How can I achieve what I need? Thank you!
The pad argument also takes negative values to bring the ticklabels closer to the ticks.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
fig = plt.figure()
ax = axes3d.Axes3D(fig)
ax.set_xlabel("X" , fontsize=20)
ax.set_ylabel("Y", fontsize=20)
ax.set_zlabel("Z" , fontsize=20)
ax.view_init(azim=-20)
ax.tick_params(axis='x', which='major', pad=-5)
x = np.arange(0, 10, 0.01)
y = np.ones(len(x))
z = np.sin(x)
plt.plot(x, y, z)
plt.show()
EDIT: Alternative outcome with set figure size and dpi value.
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
mpl.rcParams["figure.figsize"] = 10, 10
mpl.rcParams["figure.dpi"] = 100
fig = plt.figure()
ax = axes3d.Axes3D(fig)
ax.set_xlabel("X" , fontsize=20)
ax.set_ylabel("Y", fontsize=20)
ax.set_zlabel("Z" , fontsize=20)
ax.view_init(azim=-20)
ax.tick_params(axis='x', which='major', pad=-5)
x = np.arange(0, 10, 0.01)
y = np.ones(len(x))
z = np.sin(x)
plt.plot(x, y, z)
plt.show()

How to define zorder when using 2 y-axis?

I plot using two y-axis, on the left and the right of a matplotlib figure and use zorder to control the position of the plots. I need to define the zorder across axes in the same figure.
Problem
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.01)
fig, ax1 = plt.subplots( 1, 1, figsize=(9,3) )
ax1.plot( x, np.sin(x), color='red', linewidth=10, zorder=1 )
ax2 = ax1.twinx()
ax2.plot( x, x, color='blue', linewidth=10, zorder=-1)
In the previous diagram, I would expect the blue line to appear behind the red plot.
How do I control the zorder when using twin axes?
I am using:
python: 3.4.3 + numpy: 1.11.0 + matplotlib: 1.5.1
This should work
ax1.set_zorder(ax2.get_zorder()+1)
ax1.patch.set_visible(False)
the following codes works
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker as tick
x = np.arange(-10,10,0.01)
plt.figure(figsize=(10, 5))
fig = plt.subplot(111)
"""be attention to here. it's fig.plot, not ax1.plot
if you write ax1.plot, then it does not work.
"""
fig.plot(x, x, color ='blue', linewidth =10)
ax2 = fig.twinx()
ax2.plot(x, np.sin(x), color='red', linewidth =10)
"""
It looks like the two axes have separate z-stacks.
The axes are z-ordered with the most recent axis on top
"""
fig.set_zorder(ax2.get_zorder()+1)
fig.patch.set_visible(False)
plt.show()
It looks like the two axes have separate z-stacks. The axes are z-ordered with the most recent axis on top, so you need to move the curve you want on top to the last axis you create:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10,0.01)
fig, ax1 = plt.subplots( 1, 1, figsize=(9,3) )
ax1.plot( x, x, color='blue', linewidth=10 )
ax2 = ax1.twinx()
ax2.plot( x, np.sin(x), color='red', linewidth=10 )

How to set fontsize of axis label with LaTex symbol on matplotlib/seaborn?

In matplotlib, how can I change the font size of a latex symbol?
I have the following code:
import matplotlib.pyplot as plt
import seaborn as sns
# get x and y from file
plt.plot(x, y, linestyle='--', marker='o', color='b')
plt.xlabel(r'$\alpha$ (distance weighted)', fontsize='large')
plt.ylabel('AUC')
plt.show()
But I get the following graph:
Notice that the $\alpha$ is still small.
To increase the size of the fonts set the desired value to fontsize. One way to mitigate the difference between the "normal" font and the "latex" one is by using \mathrm. The example below shows the behaviour of doing this:
import matplotlib.pyplot as plt
import seaborn as sns
x = np.arange(10)
y = np.random.rand(10)
fig = plt.figure(1, figsize=(10,10))
for i, j in zip(np.arange(4), [10,15,20,30]):
ax = fig.add_subplot(2,2,i+1)
ax.plot(x, y, linestyle='--', marker='o', color='b')
ax.set_xlabel(r'$\mathrm{\alpha \ (distance \ weighted)}$', fontsize=j)
ax.set_ylabel('AUC')
plt.show()

python: scatter plot logarithmic scale

In my code, I take the logarithm of two data series and plot them. I would like to change each tick value of the x-axis by raising it to the power of e (anti-log of natural logarithm).
In other words. I want to graph the logarithms of both series but have x-axis in levels.
Here is the code that I'm using.
from pylab import scatter
import pylab
import matplotlib.pyplot as plt
import pandas as pd
from pandas import Series, DataFrame
import numpy as np
file_name = '/Users/joedanger/Desktop/Python/scatter_python.csv'
data = DataFrame(pd.read_csv(file_name))
y = np.log(data['o_value'], dtype='float64')
x = np.log(data['time_diff_day'], dtype='float64')
fig = plt.figure()
plt.scatter(x, y, c='blue', alpha=0.05, edgecolors='none')
fig.suptitle('test title', fontsize=20)
plt.xlabel('time_diff_day', fontsize=18)
plt.ylabel('o_value', fontsize=16)
plt.xticks([-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4])
plt.grid(True)
pylab.show()
let matplotlib take the log for you:
fig = plt.figure()
ax = plt.gca()
ax.scatter(data['o_value'] ,data['time_diff_day'] , c='blue', alpha=0.05, edgecolors='none')
ax.set_yscale('log')
ax.set_xscale('log')
If you are using all the same size and color markers, it is faster to use plot
fig = plt.figure()
ax = plt.gca()
ax.plot(data['o_value'] ,data['time_diff_day'], 'o', c='blue', alpha=0.05, markeredgecolor='none')
ax.set_yscale('log')
ax.set_xscale('log')
The accepted answer is a bit out of date. At least pandas 0.25 natively supports log axes:
# logarithmic X
df.plot.scatter(..., logx=True)
# logarithmic Y
df.plot.scatter(..., logy=True)
# both
df.plot.scatter(..., loglog=True)

Categories