My plot is like the following
fig = plt.figure(figsize=(7,3))
ax1 = fig.add_subplot(1,3,1)
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)
ax1.scatter(x11, y11, s=50, alpha=0.5, c='orange', marker='o')
ax1.scatter(x12, y12, s=50, alpha=0.5, c='blue', marker='s')
ax2.scatter(x21, y21, s=50, alpha=0.5, c='orange', marker='o')
ax2.scatter(x22, y22, s=50, alpha=0.5, c='blue', marker='s')
ax3.scatter(x31, y31, s=50, alpha=0.5, c='orange', marker='o')
ax3.scatter(x32, y32, s=50, alpha=0.5, c='blue', marker='s')
It seems kinda redundant to set s=50, alpha=0.5 over and over. Is there a way to set them once for all? Also for color and marker, is there a way to write them in one place so it's easier to modify?
You could do this:
fig = plt.figure(figsize=(7,3))
ax1 = fig.add_subplot(1,3,1)
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)
xs = [x11, x12, x21, x22, x31, x32]
ys = [y11, y12, y21, y22, y31, y32]
cs = ['orange', 'blue']
ms = 'os'
for j in xrange(len(xs)):
ax1.scatter(xs[j], ys[j], s=50, alpha=0.5, c=cs[j % 2], marker=ms[j % 2])
I like organizing the data and styles, and then using that to organize the plotting. Generating some random data to make a runnable example:
import matplotlib.pyplot as plt
from numpy.random import random
fig, axs = plt.subplots(3, figsize=(7,3)) #axs is an array of axes
orange_styles = {'c':"orange", 'marker':'o'}
blue_styles = {'c':"blue", 'marker':'s'}
pts = []
for i in range(12):
pts.append(random(4))
orange_x = pts[0:3] # organized data is lists of lists
orange_y = pts[3:6]
blue_x = pts[6:10]
blue_y = pts[10:12]
for ax, x, y in zip(axs, orange_x, orange_y): #all the orange cases
ax.scatter(x, y, s=50, alpha=0.5, **orange_styles) # **kwds
for ax, x, y in zip(axs, blue_x, blue_y):
ax.scatter(x, y, s=50, alpha=0.5, **blue_styles)
Related
This is cod for plotting.
Here I have two problems.
import matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#### part where data are loaded and defined######
tab1 = pd.read_table("tab1.txt", delim_whitespace=True)
tab2 = pd.read_table("tab2.txt", delim_whitespace=True)
delen = (tab1['val2'] / tab1['val3']) *10**9
dist = tab1['val1']
size = abs(tab1['val4'])
m_Es_S0s = tab2['m1'][tab2['#type']==1]
r_Es_S0s = tab2['r1'][tab2['#type']==1]
m_dEs_dS0s = tab2['m1'][tab2['#type']==2]
r_dEs_dS0s = tab2['r1'][tab2['#type']==2]
m_dSphs = tab2['m1'][tab2['#type']==3]
r_dSphs = tab2['r1'][tab2['#type']==3]
m_Nuclear_SC = tab2['m1'][tab2['#type']==4]
r_Nuclear_SC = tab2['r1'][tab2['#type']==4]
m_GCs_UCDs_cEs = tab2['m1'][tab2['#type']==5]
r_GCs_UCDs_cEs = tab2['r1'][tab2['#type']==5]
m_YMCs = tab2['m1'][tab2['#type']==7]
r_YMCs = tab2['r1'][tab2['#type']==7]
#####part related to figure #########
fig1 = plt.figure(figsize=(10,8),dpi=100)
ax = plt.subplot()
ax.tick_params(axis='both', which='both', direction="in")
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xscale('log')
plt.yscale('log')
plt.scatter(delen ,delen/(2*3.141592653*size**2), marker='o', s=80, c=dist, cmap='Greys_r', alpha=0.9, norm=matplotlib.colors.LogNorm(), edgecolors='darkorchid', linewidth=0.5)
a1=plt.scatter(m_Es_S0s ,m_Es_S0s/(2*3.141592653*r_Es_S0s**2), marker='o', facecolors='none', edgecolors='mediumblue', linewidth=0.5, s=20)
a2=plt.scatter(m_dEs_dS0s ,m_dEs_dS0s/(2*3.141592653*r_dEs_dS0s**2), marker='o', facecolors='none', edgecolors='lightgreen', linewidth=0.5, s=20)
#a3=plt.scatter(m_dSphs ,m_dSphs/(2*3.141592653*r_dSphs**2), marker='o', facecolors='none', edgecolors='red', linewidth=0.5, s=20)
a4=plt.scatter(m_Nuclear_SC ,m_Nuclear_SC/(2*3.141592653*r_Nuclear_SC**2), marker='o', facecolors='none', edgecolors='dodgerblue', linewidth=0.8, s=20)
#a5=plt.scatter(m_GCs_UCDs_cEs ,m_GCs_UCDs_cEs/(2*3.141592653*r_GCs_UCDs_cEs**2), marker='o', facecolors='none', edgecolors='dimgrey', linewidth=0.5, s=20)
a6=plt.scatter(m_YMCs ,m_YMCs/(2*3.141592653*r_YMCs**2), marker='o', facecolors='none', edgecolors='olive', linewidth=0.7, s=20)
plt.clim(1.8,6.8)
cb = plt.colorbar(pad=0.004)
cb.set_label(label='dist', size='medium', weight='bold')
cb.ax.tick_params(labelsize='large',direction='in')
plt.ylabel('yaxis', fontsize=18)
plt.xlabel('xaxis', fontsize=18)
plt.show()
Resulting plot looks like this:
But, after uncommenting a3 and a5 (so, including more data points on the plot) I am losing all minor ticks on my plot. Figure looks like this
This is first problem why I am losing minor ticks I would like to keep them. Also I would like to keep all markers .... 10^5,10^6,10^7 ......
Another problem is that color bar does not change color. You can notice that my cmap='Greys_r' and points on the plot are ok, but color bar keeps viridis all the time.
How to change color bar to Greys_r?
Tab1 and Tab2 are here:
https://www.dropbox.com/s/gwj72blzallqjl5/tab1.txt?dl=0
https://www.dropbox.com/s/mj4fr8hetsb45eo/tab2.txt?dl=0
Try this, it seems to work.
import matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#### part where data are loaded and defined######
tab1 = pd.read_table("tab1.txt", delim_whitespace=True)
tab2 = pd.read_table("tab2.txt", delim_whitespace=True)
delen = (tab1['val2'] / tab1['val3']) *10**9
dist = tab1['val1']
size = abs(tab1['val4'])
m_Es_S0s = tab2['m1'][tab2['#type']==1]
r_Es_S0s = tab2['r1'][tab2['#type']==1]
m_dEs_dS0s = tab2['m1'][tab2['#type']==2]
r_dEs_dS0s = tab2['r1'][tab2['#type']==2]
m_dSphs = tab2['m1'][tab2['#type']==3]
r_dSphs = tab2['r1'][tab2['#type']==3]
m_Nuclear_SC = tab2['m1'][tab2['#type']==4]
r_Nuclear_SC = tab2['r1'][tab2['#type']==4]
m_GCs_UCDs_cEs = tab2['m1'][tab2['#type']==5]
r_GCs_UCDs_cEs = tab2['r1'][tab2['#type']==5]
m_YMCs = tab2['m1'][tab2['#type']==7]
r_YMCs = tab2['r1'][tab2['#type']==7]
#####part related to figure #########
fig1 = plt.figure(figsize=(10,8),dpi=100)
ax = plt.subplot()
ax.tick_params(axis='both', which='both', direction="in")
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xscale('log')
plt.yscale('log')
cc = plt.scatter(delen ,delen/(2*3.141592653*size**2), marker='o', s=80, c=dist, cmap='Greys_r', alpha=0.9, norm=matplotlib.colors.LogNorm(), edgecolors='darkorchid', linewidth=0.5)
a1=plt.scatter(m_Es_S0s ,m_Es_S0s/(2*3.141592653*r_Es_S0s**2), marker='o', facecolors='none', edgecolors='mediumblue', linewidth=0.5, s=20)
a2=plt.scatter(m_dEs_dS0s ,m_dEs_dS0s/(2*3.141592653*r_dEs_dS0s**2), marker='o', facecolors='none', edgecolors='lightgreen', linewidth=0.5, s=20)
a3=plt.scatter(m_dSphs ,m_dSphs/(2*3.141592653*r_dSphs**2), marker='o', facecolors='none', edgecolors='red', linewidth=0.5, s=20)
a4=plt.scatter(m_Nuclear_SC ,m_Nuclear_SC/(2*3.141592653*r_Nuclear_SC**2), marker='o', facecolors='none', edgecolors='dodgerblue', linewidth=0.8, s=20)
a5=plt.scatter(m_GCs_UCDs_cEs ,m_GCs_UCDs_cEs/(2*3.141592653*r_GCs_UCDs_cEs**2), marker='o', facecolors='none', edgecolors='dimgrey', linewidth=0.5, s=20)
a6=plt.scatter(m_YMCs ,m_YMCs/(2*3.141592653*r_YMCs**2), marker='o', facecolors='none', edgecolors='olive', linewidth=0.7, s=20)
plt.clim(1.8,6.8)
cb = plt.colorbar(cc,pad=0.004)
cb.set_label(label='dist', size='medium', weight='bold')
#cb.ax.tick_params(labelsize='large',direction='in')
import matplotlib.ticker
## set y ticks
y_major = matplotlib.ticker.LogLocator(base = 10, numticks = 15)
ax.yaxis.set_major_locator(y_major)
y_minor = matplotlib.ticker.LogLocator(base = 10, subs = np.arange(1.0, 10.0) * 0.1, numticks = 20)
ax.yaxis.set_minor_locator(y_minor)
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
x_major = matplotlib.ticker.LogLocator(base = 10, numticks = 15)
ax.xaxis.set_major_locator(x_major)
x_minor = matplotlib.ticker.LogLocator(base = 10, subs = np.arange(1.0, 10.0) * 0.1, numticks = 20)
ax.xaxis.set_minor_locator(x_minor)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
plt.ylabel('yaxis', fontsize=18)
plt.xlabel('xaxis', fontsize=18)
#plt.savefig("out1.png")
plt.show()
Output fig is here.
enter image description here
I have three point plot i'm trying to chart and show a legend. The colors do not match the colors called out in the plots. I tried using the solution from this post, but that did not work.
Here is the code I'm using:
fig, ax = plt.subplots()
a = sns.pointplot(x=l[1:], y = np.exp(model_m.params[1:]), label = 'factor',
ax = ax, color = 'green')
b = sns.pointplot(x=l[1:], y = np.exp(model_m.conf_int()[1:][:,1]),
ax = ax, label = 'conf_int+', color = 'red')
c = sns.pointplot(x=l[1:], y = np.exp(model_m.conf_int()[1:][:,0]),
ax = ax, label = 'conf_int-', color = 'blue')
plt.title('Model M Discrete')
ax.legend(labels = ['factor', 'conf_inf+', 'conf_inf-'],
title = 'legend')
Here is what it produces:
The easiest solution would be to use sns.lineplot instead of sns.pointplot:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
fig, ax = plt.subplots()
x = np.arange(10)
sns.lineplot(x=x, y=1 + np.random.rand(10).cumsum(),
ax=ax, label='factor', color='green', marker='o')
sns.lineplot(x=x, y=2 + np.random.rand(10).cumsum(),
ax=ax, label='conf_int+', color='red', marker='o')
sns.lineplot(x=x, y=3 + np.random.rand(10).cumsum(),
ax=ax, label='conf_int-', color='blue', marker='o')
ax.set_title('Model M Discrete')
ax.legend(title='legend')
plt.tight_layout()
plt.show()
Another option would be to iterate through the generated "pathCollections" and assign a label (for some reason label= doesn't work in sns.pointplot).
fig, ax = plt.subplots()
sns.pointplot(x=x, y=1 + np.random.rand(10).cumsum(),
ax=ax, color='green')
sns.pointplot(x=x, y=2 + np.random.rand(10).cumsum(),
ax=ax, color='red')
sns.pointplot(x=x, y=3 + np.random.rand(10).cumsum(),
ax=ax, label='conf_int-', color='blue')
for curve, label in zip(ax.collections, ['factor', 'conf_int+', 'conf_int-']):
curve.set_label(label)
ax.set_title('Model M Discrete')
ax.legend(title='legend')
Still another way is to mimic a long form dataframe with hue which automatically creates a legend:
fig, ax = plt.subplots()
x = np.arange(10)
y1 = 1 + np.random.rand(10).cumsum()
y2 = 2 + np.random.rand(10).cumsum()
y3 = 3 + np.random.rand(10).cumsum()
sns.pointplot(x=np.tile(x, 3),
y=np.concatenate([y1, y2, y3]),
hue=np.repeat(['factor', 'conf_int+', 'conf_int-'], len(x)),
ax=ax, palette=['green', 'red', 'blue'])
Note that in both cases only a dot is shown in the legend, not a line.
I create two scatterplots with matplotlib in python with this code, the data for the code is here:
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
fig = plt.figure(figsize=(20,12))
ax1 = fig.add_subplot(111)
ax3 = ax1.twinx()
norm = Normalize(vmin=0.95*min(arr), vmax=1.05*max(arr))
ax1.scatter(x, y1, s=20, c=arr, cmap='Blues_r', norm=norm, marker='x', label='bla1')
ax3.scatter(x, y2, s=(20*(1.1-arr))**3.5, c=arr, cmap='Reds_r', norm=norm, marker='^', label='bla1')
The created fig. looks like this:
So, the dot size (in ax3) and the dot colour (in ax1 and ax3) are taken from arrays containing floats with all kinds of values in the range [0,1]. My question: How do I create a legend that displays the corresponding y-values for, let's say 5 different dot sizes and 5 different colour nuances?
I would like the legend to look like in the figure below (source here), but with the colour bar and size bar put into a single legend, if possible. Thanks for suggestions and code!
# using your data in dataframe df
# create s2
df['s2'] = (20*(1.1-df.arr))**3.5
fig = plt.figure(figsize=(20,12))
ax1 = fig.add_subplot(111)
ax3 = ax1.twinx()
norm = Normalize(vmin=0.95*min(df.arr), vmax=1.05*max(df.arr))
p1 = ax1.scatter(df.x, df.y1, s=20, c=df.arr, cmap='Blues_r', norm=norm, marker='x')
fig.colorbar(p1, label='arr')
p2 = ax3.scatter(df.x, df.y2, s=df.s2, c=df.arr, cmap='Reds_r', norm=norm, marker='^')
fig.colorbar(p2, label='arr')
# create the size legend for red
for x in [15, 80, 150]:
plt.scatter([], [], c='r', alpha=1, s=x, label=str(x), marker='^')
plt.legend(loc='upper center', bbox_to_anchor=(1.23, 1), ncol=1, fancybox=True, shadow=True, title='s2')
plt.show()
There's no legend for p1 because the size is static.
I think this would be better as two separate plots
I used Customizing Plot Legends: Legend for Size of Points
Separate
fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(20, 10))
norm = Normalize(vmin=0.95*min(df.arr), vmax=1.05*max(df.arr))
p1 = ax1.scatter(df.x, df.y1, s=20, c=df.arr, cmap='Blues_r', norm=norm, marker='x')
fig.colorbar(p1, ax=ax1, label='arr')
p2 = ax2.scatter(df.x, df.y2, s=df.s2, c=df.arr, cmap='Reds_r', norm=norm, marker='^')
fig.colorbar(p2, ax=ax2, label='arr')
# create the size legend for red
for x in [15, 80, 150]:
plt.scatter([], [], c='r', alpha=1, s=x, label=str(x), marker='^')
plt.legend(loc='upper center', bbox_to_anchor=(1.2, 1), ncol=1, fancybox=True, shadow=True, title='s2')
plt.show()
I want to plot some data I have (square wave signals) in a subplot but I want to remove the axis for better visualization. This results in not having a ylabel. I thought I could add a simple text() so I could manually insert the text I want, but I can't seem to be able to use negative values for the y axis (as I could without a subplot). The code I thought would work was:
fig, (ax1, ax2, ax3, ax4, ax5, ax6)= plt.subplots(6,1)
#plot
ax1.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.clk_y, linewidth=2, color='black')
ax2.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.clkbar_y, linewidth=2, color='black')
ax3.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.q1_y, linewidth=2, color='C0')
ax4.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.q2_y, linewidth=2, color='C1')
ax5.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.q1bar_y, linewidth=2, color='C2')
ax6.plot(PathClockGeneration_4.q2bar_x,PathClockGeneration_4.q2bar_y, linewidth=2, color='C3')
#axis
ax1.axis('off')
ax2.axis('off')
ax3.axis('off')
ax4.axis('off')
ax5.axis('off')
ax6.axis('off')
#text
ax1.text(-1.5, 2, 'MyText')
If i try the last line as ax1.text(0, 2, 'MyText') it works fine, but the placement of the text is not the one I want. I suppose this comes from the size my plot is allowed to have and I would need to change it, how to do so?
EDIT
This is what I obtain hiding the axis manually (which can allow me to insert a ylabel). This is what I really want as plot obtained from the coded posted above by commenting ax1.text(-1.5, 2, 'MyText')
You can use fig instead of the ax1 to place your text. The arguments 0.05, 0.6 are the x and y coordinates in relative scale. You can choose them as per your taste.
Complete answer
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6,1)
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
ax1.plot(x, y, linewidth=2, color='black')
ax2.plot(x, y, linewidth=2, color='black')
ax3.plot(x, y, linewidth=2, color='C0')
ax4.plot(x, y, linewidth=2, color='C1')
ax5.plot(x, y, linewidth=2, color='C2')
ax6.plot(x, y, linewidth=2, color='C3')
# Hiding axis
for ax in [ax1, ax2, ax3, ax4, ax5, ax6]:
ax.axis('off')
fig.text(0.05, 0.6, 'MyText', rotation=90, fontsize=20)
plt.show()
I am trying to make this animated so that the dot and the green line move due to the for loop. This code displays 3 different graphs one below the other. The middle graph has no animation section.
x =lag_range
count = 0
plt.ion()
fig, ax = plt.subplots()
for b in x:
plt.subplot(311)
plt.plot(x,pear_corr, color='b', linewidth=1.5, label ='Pearson')
plt.plot(x,spear_corr, color ='r', linewidth=1.5, label='Spearman')
plt.plot(x[count],pear_corr[count],'yo')
plt.legend()
axes = plt.gca()
plt.ylabel('Correlation coefficients')
plt.xlabel('Lag times /days')
axes.set_xlim([min(lag_list),last])
axes.set_ylim(-1,1)
plt.subplot(312)
plt.plot(x,pear_p_values, color='b', linewidth=1.5)
plt.plot(x,spear_p_values, color ='r', linewidth=1.5)
axes = plt.gca()
plt.ylabel('P values')
plt.xlabel('Lag times /days')
axes.set_xlim([min(lag_list),last])
plt.subplot(313)
ax1 = plt.subplot(313)
x_for_p = range(len(x_prices))
ax1.plot(x_for_p, x_prices, color ='grey', linewidth=1.5)
ax1.set_ylabel('Share price', color ='grey')
ax1.tick_params('y', colors='grey')
ax1.set_xlabel('Days')
axes = plt.gca()
axes.set_xlim([min(lag_list),(2*last)])
ax2 = ax1.twinx()
x_for_den = range(b,(b+len(x_prices)))
ax2.plot(x_for_den, y_planes, color='g', linewidth=1.5)
ax2.set_ylabel('Plane density', color='g')
ax2.tick_params('y', colors='g')
count += 1
plt.pause(2)
plt.draw()
cross_corr2_vis(prices, density_p3)
If you could share a working code or just definitions of variables pear_corr, spear_corr, etc., the following code might have not resulted in this simple animation:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
N_points = 1000
x = np.linspace(0,2.*np.pi,N_points)
y = np.sin(x)
fig, ax = plt.subplots()
ax.set_xlim([0,2.*np.pi])
ax.set_ylim([-1,1])
line, = ax.plot( [],[], lw=2, color='g')
sctr = ax.scatter([],[], s=100, color='r')
def animate(i):
line.set_ydata(y[:i+1]) # update
line.set_xdata(x[:i+1])
sctr.set_offsets((x[i],y[i]))
return line,sctr
ani = animation.FuncAnimation(fig, animate, N_points, interval=5, blit=True)
plt.show()