How to customize a Graph using Matplotlib - python-3.x

I need help to customize a graph using Matplotlib.
I want to draw a graph like this.
My python code is:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
data=np.loadtxt('input.txt', delimiter = ',')
x = np.arange(0,64)
y = np.arange(0,64)
fig, ax = plt.subplots()
im = ax.imshow(data)
#customize colorbar
cmap = mpl.colors.ListedColormap(['royalblue','blue','red'])
im = ax.contourf(y,x,data,cmap=cmap)
fig.colorbar(im)
plt.show()
and my output is:
So what should i do ?
Thank you.

Related

Can I generate a contourplot from three columns of data in python without using meshgrid?

I have three columns of data. They are too large to generate meshgrids from. So e.g. in order to generate a surface plot from the data, I use a method like so
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
x, y, z = np.loadtxt('data_file', unpack=True)
df = pd.DataFrame({'x':x, 'y':y, 'z':z})
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_trisurf(df.x, df.y, df.z, cmap=cm.jet, linewidth=0.05)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
Is there a similar alternative to plot_trisurf for contours?

How to add color and legend by points' label one by one in python?

I want to divide and color points,val_lab(611,3) by their labels,pred_LAB(611,)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = plt.axes(projection = '3d')
ax.set_xlabel('L')
ax.set_ylabel('A')
ax.set_zlabel('B')
for i in range(0, len(val_lab)):
ax.scatter3D(
val_lab[i,0],
val_lab[i,1],
val_lab[i,2],
s = 8,
marker='o',
c = pred_LAB
#cmap = 'rainbow'
)
#ax.legend(*points.legend_elements(), title = 'clusters')
plt.show()
The problem is it shows error,
c' argument has 611 elements, which is not acceptable for use with 'x'
with size 1, 'y' with size 1.
However, if the dataset only have ten points,it can show the figure correctly, I don't know how to solve this problem, besides, how to add legend of this figure?
In your solution you would want to replace c = pred_LAB with c = pred_LAB[i]. But you do not have to use a for loop to plot the data. You can just use the following:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# generate random input data
val_lab = np.random.randint(0,10,(611,3))
pred_LAB = np.random.uniform(0,1, (611,))
# plot data
fig = plt.figure()
ax = plt.axes(projection = '3d')
ax.set_xlabel('L')
ax.set_ylabel('A')
ax.set_zlabel('B')
# create one 3D scatter plot - no for loop
ax.scatter3D(
val_lab[:,0],
val_lab[:,1],
val_lab[:,2],
s = 8,
marker='o',
c = pred_LAB,
cmap = 'rainbow',
label='my points'
)
# add legend
plt.legend()
plt.show()

Python figure with the entire set of labels

I am trying to generate a figure to visualize the entire covariance matrix.
However, I am not able to include the entire list of labels. See the working example below:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm as cm
numberYears=len(range(2002,2018+1))
covMatrix=np.ones([numberYears,numberYears])
for count1,year1 in enumerate(range(2002,2018+1)) :
for count2,year2 in enumerate(range(2002,2018+1)) :
covMatrix[count1,count2]=1-(abs(count1-count2)/numberYears)
fig = plt.figure()
ax1 = fig.add_subplot(111)
cmap = cm.get_cmap('rainbow', 30)
cax = ax1.imshow(covMatrix, interpolation="nearest", cmap=cmap)
labels=[]
for year in range(2002,2018+1):
labels.append(str(year))
ax1.set_xticklabels(labels,fontsize=10,rotation=90)
ax1.set_yticklabels(labels,fontsize=10)
fig.colorbar(cax, ticks=[.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0])
fig.savefig('map.png')
Note that my labels are [2002,2003,...,2017,2018] and the entire list is not included as a label of the figure. How can I deal with this?
Considering #ImportanceOfBeingErnest comment, I was able to find the solution. I include the argument "extent" in the function "imshow" and I also "set.xticks":
from matplotlib import pyplot as plt
from matplotlib import cm as cm
numberYears=len(range(2002,2018+1))
covMatrix=np.ones([numberYears,numberYears])
for count1,year1 in enumerate(range(2002,2018+1)) :
for count2,year2 in enumerate(range(2002,2018+1)) :
covMatrix[count1,count2]=1-(abs(count1-count2)/numberYears)
fig = plt.figure()
ax1 = fig.add_subplot(111)
cmap = cm.get_cmap('rainbow', 30)
cax = ax1.imshow(covMatrix, interpolation="nearest", cmap=cmap,extent=[2002,2018,2002,2018])
labels=[]
for year in range(2002,2018+1):
labels.append(str(year))
ax1.set_xticks(listYears)
ax1.set_yticks(listYears)
ax1.set_xticklabels(labels,fontsize=10,rotation=90)
ax1.set_yticklabels(labels,fontsize=10)
fig.colorbar(cax, ticks=[.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0])
fig.savefig('mapTeste.png')

how can i plot the graph for csv data in matplotlib

can you please tell me how to plot the graph for csv data.
csv file have x,y,depth,color values i want to plot the depth and color for x and y axis,i goggled many times but i didn't find anything properly.so please guide me how to plot the graph for that values?
this is i tried :
from matplotlib import pyplot as plt
from matplotlib import style
import pandas as pd
data=pd.read_csv("Tunnel.csv",names=['x','y','z','color'])
data1 =data[data.z==0]
print (data1)
# plt.plot(data[data.x],data[data.y])
plt.ylabel('yaxis')
plt.xlabel('xaxis')
plt.title('Tunnel 2d')
plt.show()
my data is given bellow
I'm assuming that you want the first two columns to be used as plot axis and columns 3 and 4 as plot data.
from matplotlib import pyplot as plt
import pandas as pd
data = pd.read_csv("Tunnel.csv")
x = stats[stats.columns[2]]
y = stats[stats.columns[3]]
xlab = list(stats)[0] #x-axis label
ylab = list(stats)[1] #y-axis label
fig, pli = plt.subplots()
pli.show()
#Assuming it's a line graph that you want to plot
line, = pli.plot(x, y, color='g', linewidth=5, label='depth vs color')
plt.xlabel(xlab)
plt.ylabel(ylab)
plt.title(title)
fig.savefig('./Directory/Graph.png')
I am assuming that you want the color and depth as text annotations.
import stuff
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
create the df
dep=list(np.random.randint(0,100,10))
col=list(np.random.randint(0,100,10))
y=[int(x/3)+1 for x in range(0,10)]
x=list(range(0,10))
my_df=pd.DataFrame({'x':x,'y':y,'colour':col,'depth':dep})
create the annotate column
my_df['my_text']='c= '+my_df.colour.astype(str)+','+'d= '+my_df.depth.astype(str)
plot it
plt.figure(figsize=(20,10))
plt.plot(my_df.x,my_df.y,'o')
for i, txt in enumerate(my_df['my_text']):
plt.annotate(txt, (x[i],y[i]), size=10, xytext=(0,0), ha='left', textcoords='offset points', bbox=dict(facecolor='none', edgecolor='red'))
plt.ylabel('yaxis')
plt.xlabel('xaxis')
plt.title('Tunnel 2d')
plt.show()
Result

Seaborn Heatmap Colorbar Label as Percentage

Given this heat map:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)
How would I go about making the color bar values display in percent format?
Also, what if I just wanted to show the first and last values on the color bar?
Thanks in advance!
iterating on the solution of #mwaskom, without creating the colorbar yourself:
import numpy as np
import seaborn as sns
data = np.random.rand(8, 12)
ax = sns.heatmap(data, vmin=0, vmax=1)
cbar = ax.collections[0].colorbar
cbar.set_ticks([0, .2, .75, 1])
cbar.set_ticklabels(['low', '20%', '75%', '100%'])
Well, I had a similar problem and figured out how to properly set a formatter. Your example would become something like:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
uniform_data = 100 * uniform_data
sns.heatmap(uniform_data,
cbar_kws={'format': '%.0f%%'})
So, what you have to do is to pass an old-style string formatter to add percentages to colorbar labels. Not exactly what I would name self-evident, but works...
To show only the first and last, then you add vmax, vmin and an extra parameter to cbar_kws:
sns.heatmap(uniform_data,
cbar_kws={'format': '%.0f%%', 'ticks': [0, 100]},
vmax=100,
vmin=0)
You should get the colour bar object and then get the relevant axis object:
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
fig, ax = plt.subplots()
sns.heatmap(df, ax=ax, cbar_kws={'label': 'My Label'})
cbar = ax.collections[0].colorbar
cbar.ax.yaxis.set_major_formatter(PercentFormatter(1, 0))
You need to be able to access the colorbar object. It might be buried in the figure object somewhere, but I couldn't find it, so the easy thing to do is just to make it yourself:
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, cbar=False, vmin=0, vmax=1)
cbar = ax.figure.colorbar(ax.collections[0])
cbar.set_ticks([0, 1])
cbar.set_ticklabels(["0%", "100%"])

Resources