matplotlib show incomplete tick labels - python

I need use Matplotlib to draw headmaps with chinese tick labels. But the result shows incomplete tick labels as below. I don't know why it happened. I tried to change other chinese font but doesn't work. How to fix it?
import numpy as np
import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['STZhongsong']
mpl.rcParams['axes.unicode_minus'] = True
def heatmap(data, row_labels, col_labels, ax=None,
cbar_kw={}, cbarlabel="", **kwargs):
if not ax:
ax = plt.gca()
im = ax.imshow(data, **kwargs)
cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)
cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")
ax.set_xticks(np.arange(data.shape[1]))
ax.set_yticks(np.arange(data.shape[0]))
ax.set_xticklabels(col_labels)
ax.set_yticklabels(row_labels)
ax.tick_params(top=True, bottom=False,
labeltop=True, labelbottom=False)
plt.setp(ax.get_xticklabels(), rotation=-20, ha="right",
rotation_mode="anchor")
for edge, spine in ax.spines.items():
spine.set_visible(False)
ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)
ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)
ax.grid(which="minor", color="w", linestyle='-', linewidth=3)
ax.tick_params(which="minor", bottom=False, left=False)
return im, cbar
if __name__ == "__main__":
x,y = list("你这是干什么啦?"),list("你要吃什么?")
s = np.random.random([len(x), len(y)])
fig, ax = plt.subplots()
im, cbar = heatmap(s, x, y, ax=ax,
cmap="YlGn", cbarlabel="attention scores")
fig.tight_layout()
plt.savefig("test", dpi=300, bbox_inches = 'tight')
plt.show()

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as mfm
import matplotlib.pyplot as plt
def heatmap(data, row_labels, col_labels, ax=None,
cbar_kw={}, cbarlabel="", **kwargs):
if not ax:
ax = plt.gca()
im = ax.imshow(data, **kwargs)
cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)
cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")
ax.set_xticks(np.arange(data.shape[1]))
ax.set_yticks(np.arange(data.shape[0]))
font_path = "/Downloads/ZCOOLXiaoWei-Regular.ttf"
prop = mfm.FontProperties(fname=font_path)
ax.set_xticklabels(col_labels,fontproperties=prop,fontsize=50)
ax.set_yticklabels(row_labels,fontproperties=prop,fontsize=50)
ax.tick_params(top=True, bottom=False,
labeltop=True, labelbottom=False)
plt.setp(ax.get_xticklabels(), rotation=-20, ha="right",
rotation_mode="anchor")
for edge, spine in ax.spines.items():
spine.set_visible(False)
ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)
ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)
ax.grid(which="minor", color="w", linestyle='-', linewidth=3)
ax.tick_params(which="minor", bottom=False, left=False)
return im, cbar
if __name__ == "__main__":
x,y = list("你这是干什么啦"),list("你这是干什么啦")
s = np.random.random([len(x), len(y)])
fig, ax = plt.subplots(figsize=(10,10))
im, cbar = heatmap(s, x, y, ax=ax,
cmap="YlGn", cbarlabel="attention scores")
fig.tight_layout()
plt.savefig("test", dpi=300, bbox_inches = 'tight')
plt.show()
I have made few changes in the code and used the matplotlib.font_manager to render the Chinese font.

Related

matplotlib arrow color not work as expected

How to change the arrow color in below demo code?
import matplotlib.pyplot as plt
def save_fig(fig,pngname):
fig.savefig(pngname, dpi=fig.dpi, bbox_inches="tight")
print("[[%s]]"%pngname)
return
def add_arrow(fig,ax,lw,lc):
xmin,xmax = ax.get_xlim()
ax.arrow(xmin,0,xmax-xmin+.2,0,#fc='k', ec='k',
lw = lw,head_width=.1,head_length=0.4, overhang = 0,
length_includes_head=False, clip_on = False,edgecolor='k',facecolor=lc)
return
def main():
x = [
#"FLAGS",
"INTENDED_VSYNC",
"VSYNC",
"OLDEST_INPUT_EVENT",
"HANDLE_INPUT_START",
"ANIMATION_START",
"PERFORM_TRAVERSALS_START",
"DRAW_START",
"SYNC_QUEUED",
"SYNC_START",
"ISSUE_DRAW_COMMANDS_START",
"SWAP_BUFFERS",
"FRAME_COMPLETED",
]
lw = 2
lc = "grey"
fig, ax = plt.subplots(1, figsize=(8,.2))
y = [0]*len(x)
ax.plot(x,y,color=lc)
ax.set_ylim([0,0.1])
plt.xticks(rotation=45,ha='right')
ax.tick_params(direction = 'inout',color=lc)
ax.tick_params('both', length=20, width=lw, which='major')
ax.tick_params('both', length=10, width=lw, which='minor')
plt.yticks([], [])
for direction in ["left", "right", "bottom", "top"]:
ax.spines[direction].set_visible(False)
add_arrow(fig,ax,lw,lc)
#save_fig(fig,sdir + "/vsync.png")
plt.show()
return
sdir = "/home/tester"
main()
Output:
The color is defined in ax.arrow() by color, edgecolor and facecolor.
edgecolor sets the color of the edge of the arrow.
facecolor sets the color in the arrow body.
color sets the color of both, edgecolor and facecolor.
If you would like to have a uniformly colored arrow, you can either set color to the desired value or alternatively set both, edgecolor and facecolor to the same value. In this case it would mean removing edgecolor and facecolor and adding color=lc or alternatively replacing edgecolor='k' with edgecolor=lc.
import matplotlib.pyplot as plt
def save_fig(fig,pngname):
fig.savefig(pngname, dpi=fig.dpi, bbox_inches="tight")
print("[[%s]]"%pngname)
return
def add_arrow(fig,ax,lw,lc):
xmin,xmax = ax.get_xlim()
ax.arrow(xmin,0,xmax-xmin+.2,0,#fc='k', ec='k',
lw = lw,head_width=.1,head_length=0.4, overhang = 0,
length_includes_head=False, clip_on = False,color=lc)
return
def plot():
x = [
#"FLAGS",
"INTENDED_VSYNC",
"VSYNC",
"OLDEST_INPUT_EVENT",
"HANDLE_INPUT_START",
"ANIMATION_START",
"PERFORM_TRAVERSALS_START",
"DRAW_START",
"SYNC_QUEUED",
"SYNC_START",
"ISSUE_DRAW_COMMANDS_START",
"SWAP_BUFFERS",
"FRAME_COMPLETED",
]
lw = 2
lc = "grey"
fig, ax = plt.subplots(1, figsize=(8,.2))
y = [0]*len(x)
ax.plot(x,y,color=lc)
ax.set_ylim([0,0.1])
plt.xticks(rotation=45,ha='right')
ax.tick_params(direction = 'inout',color=lc)
ax.tick_params('both', length=20, width=lw, which='major')
ax.tick_params('both', length=10, width=lw, which='minor')
plt.yticks([], [])
for direction in ["left", "right", "bottom", "top"]:
ax.spines[direction].set_visible(False)
add_arrow(fig,ax,lw,lc)
#save_fig(fig,sdir + "/vsync.png")
plt.show()
return
plot()

Can't save Matplotlib figure correctly when using a function

This is an example of my code to plot and save a figure:
I'm using Python 3.7.4 and matplotlib==3.0.3.
import matplotlib.pyplot as plt
import pandas as pd
from yahoo_fin import stock_info
import statsmodels.api as sm
brk_data = stock_info.get_data("BRK-A")
with plt.style.context('dark_background'):
fig, ax = plt.subplots(figsize=(16, 9))
sm.qqplot(brk_data['adjclose'].pct_change(1).fillna(0), fit=True, line='45', ax=ax)
plt.title('QQ Plot', fontsize = 16)
ax.axvline(0, c = 'w', linestyle = "--", alpha = 0.5)
ax.grid(True,linewidth=0.30)
ax.set_xlim(4,-4)
ax.set_ylim(5,-5)
plt.savefig('qqplot.png', bbox_inches = 'tight', pad_inches = 0.4, dpi = 300, edgecolor = 'k')
plt.show()
plt.close()
This code saves and displays the plot figure correctly, as follows:
But when the plot is built inside a function, the saved picture background will stay white, making the white ticks and labels from the 'dark-background' style invisible, e.g.:
for
def qqplot2(pct, save = False):
with plt.style.context('dark_background'):
fig, ax = plt.subplots(figsize=(16, 9))
sm.qqplot(pct, fit=True, line='45', ax=ax)
plt.title('QQ Plot', fontsize = 16)
ax.axvline(0, c = 'w', linestyle = "--", alpha = 0.5)
ax.grid(True,linewidth=0.30)
ax.set_xlim(4,-4)
ax.set_ylim(5,-5)
if save == True:
plt.savefig('qqplot2.png', bbox_inches = 'tight', pad_inches = 0.4, dpi = 300, edgecolor = 'k')
plt.show()
plt.close()
else:
plt.show()
calling the function with qqplot2(brk_data['adjclose'].pct_change(1).fillna(0), save = True) will display the correct plot:
but will save the figure incorrectly:
You just need to indent your if clause in the function like this:
def qqplot2(pct, save = False):
with plt.style.context('dark_background'):
fig, ax = plt.subplots(figsize=(16, 9))
sm.qqplot(pct, fit=True, line='45', ax=ax)
plt.title('QQ Plot', fontsize = 16)
ax.axvline(0, c = 'w', linestyle = "--", alpha = 0.5)
ax.grid(True,linewidth=0.30)
ax.set_xlim(4,-4)
ax.set_ylim(5,-5)
if save == True:
plt.savefig('qqplot2.png', bbox_inches = 'tight', pad_inches = 0.4, dpi = 300, edgecolor = 'k')
plt.show()
plt.close()
else:
plt.show()

How to show bar chart in python

I'm trying to create a bar chart with multiple bars in Python. The bar chart should display values on top of each bar.
I have a data set like the following:
Speciality Very interested Somewhat_interested Notinterested
Big Data (Spark/Hadoop) 1332 729 127
Data Analysis / Statistics 1688 444 60
Data Journalism 429 1081 610
I have tried the following code:
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
pd_dataframe = pd.read_csv('Test-Barchart.csv')
no_of_xaxis = pd_dataframe.Speciality.nunique()
ind = np.arange(no_of_xaxis)
xcord = pd_dataframe['Speciality'].tolist()
veryinterestedlist = pd_dataframe['Very interested'].tolist()
somewhatlist = pd_dataframe['Somewhat interested'].tolist()
notinterestedlist = pd_dataframe['Not interested'].tolist()
fig=plt.figure()
ax = fig.add_subplot(111)
width=0.8
rects1 = ax.bar(ind, veryinterestedlist, width, color='r')
rects2 = ax.bar(ind, somewhatlist, width, color='g')
rects3 = ax.bar(ind+width*2, notinterestedlist, width, color='b')
ax.legend( (rects1[0], rects2[0], rects3[0]), ('Very Interested',
'Somewhat Interested', 'Not Interested') )
def autolabel(rects):
for rect in rects:
h = rect.get_height()
ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
ax.set_xticks(ind+width)
ax.set_xticklabels( xcord )
plt.show()
The problem is, plt.show() is not showing anything!
I don't have any errors in the code.
Could you please help me resolve this problem?
Also how can i change bar color to hex code color instead of r,g or b? e.g. #5bc0de
Small changes to your code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
pd_dataframe = pd.read_csv('Test-Barchart.csv')
no_of_xaxis = pd_dataframe.Speciality.nunique()
ind = np.arange(no_of_xaxis)
width = 0.1
xcord = pd_dataframe['Speciality'].tolist()
veryinterestedlist = pd_dataframe['Very interested'].tolist()
somewhatlist = pd_dataframe['Somewhat interested'].tolist()
notinterestedlist = pd_dataframe['Not interested'].tolist()
fig, ax = plt.subplots()
rects1 = ax.bar(ind, veryinterestedlist, width, color='g')
rects2 = ax.bar(ind + width, somewhatlist, width, color='c')
rects3 = ax.bar(ind+2*width, notinterestedlist, width, color='r')
# add some text for labels, title and axes ticks
ax.set_ylabel('y label')
ax.set_title('Title')
ax.set_xticks(ind + width)
ax.set_xticklabels(xcord)
ax.legend( (rects1[0], rects2[0], rects3[0]), ('Very Interested',
'Somewhat Interested', 'Not Interested') )
def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
'%d' % int(height),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
plt.show()
and you get:
Reference: Grouped bar chart with labels

how to add 2 differentfigures in mathplotlib

I have created 2 different figures(Fig1 and Fig2) in mathplotlib and saved them in pdf. Can anybody help me how to merger these 2 figures and create single figure. fig1 and fig2 has same x-Axis.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
def lc_fslg(target,position,axes,titel,exc_true,l_pos):
for axi in axes:
pp = PdfPages('output\ ' + 'lc_over_fuselage_'+ axi + '.pdf')
plt.figure()
plt.axis('off')
plt.text(0.5, 0.5, titel+str(axi), ha='center', va='center')
pp.savefig()
plt.close()
for kind in ['ground','flight']:
plot_load_flow(target, position, kind, axi.lower(), titel, exc_true, l_pos)
plt.savefig(pp, format='pdf', papertype='a4', orientation='landscape', bbox_inches='tight')
plt.close('all')
pp.close()
def plot_load_flow(target,position,kind,axe,titel,exc_true,l_pos):
d_ax_label = {'tx': 'Tx [daN]', 'ty': 'Ty [daN]', 'tz': 'Tz [daN]'
, 'mx': 'Mx [daNm]', 'my': 'My [daNm]', 'mz': 'Mz [daNm]'}
max_v=[]
min_v=[]
max_vM=[]
min_vM=[]
pos_env=[]
if(kind == 'ground'):
for pos in l_pos:
load_at_pos = target.uload_at(pos)
max = load_at_pos[axe].loc[(load_at_pos['position'] == pos) & (load_at_pos['type'] == 'X')].max()
min = load_at_pos[axe].loc[(load_at_pos['position'] == pos) & (load_at_pos['type'] == 'X')].min()
if(not(np.isnan(max))& (not(np.isnan(min)))):
max_v.append(max)
min_v.append(min)
pos_env.append(pos)
x_env = [position[pos] for pos in pos_env]
plt.clf()
fig1 = plt.figure(figsize=(15, 15))
plt.plot(x_env, max_v, 'b-', markersize=15,linewidth=3.5, label='envelope '+str(kind))
plt.plot(x_env, min_v, 'b-', markersize=15,linewidth=3.5)
if(kind == 'flight'):
for pos in l_pos:
load_at_pos = target.uload_at(pos)
max = load_at_pos[axe].loc[(load_at_pos['position'] == pos)
& ((load_at_pos['type'] == 'G') | (load_at_pos['type'] == 'M'))].max()
min = load_at_pos[axe].loc[(load_at_pos['position'] == pos)
& ((load_at_pos['type'] == 'G') | (load_at_pos['type'] == 'M'))].min()
if (not (np.isnan(max)) & (not (np.isnan(min)))):
max_vM.append(max)
min_vM.append(min)
pos_env.append(pos)
x_env = [position[pos] for pos in pos_env]
plt.clf()
fig2 = plt.figure(figsize=(15, 15))
plt.plot(x_env, max_v, 'b-', markersize=15,linewidth=3.5, label='envelope '+str(kind))
plt.plot(x_env, min_v, 'b-', markersize=15,linewidth=3.5)
plt.plot(x_env, max_vM, 'g-', markersize=15,linewidth=3.5, label='envelope '+str(kind))
plt.plot(x_env, min_vM, 'g-', markersize=15,linewidth=3.5)
# define plot layout
plt.yticks(fontsize=20)
plt.ylabel(d_ax_label[axe], fontsize=30)
plt.xticks(fontsize=20)
plt.xticks(x_env,pos_env,fontsize=20,rotation='vertical')
plt.xlabel('frame position', fontsize=30)
plt.title(titel, fontsize=20)
legend = plt.legend(shadow=True, prop={'size': 20})
plt.grid(True)
plt.tight_layout()

Pyplot zorder lost with animation

I am trying to animate different objects in the same graph using pyplot's funcanimation.
It works almost as I expect it to, except for the order in which the different elements are displayed in. So the plot curve, text and legend are shown behind the image where they are barely seen.
Here is my (not so) minimal working example:
#! /usr/bin/python
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import random
def init():
line_simu.set_data([], [])
time_text.set_text('')
imobj.set_data(np.zeros((100, 100)))
imobj.set_zorder(0)
time_text.set_zorder(10)
return line_simu, time_text, imobj
def animate(i):
imobj.set_zorder(0)
time_text.set_zorder(10)
y_simu = np.linspace(0,100, 100)
x_simu = np.linspace(-10, 10, 100)
line_simu.set_data(x_simu, y_simu)
time_text.set_text('time = %.1f' % i )
global data
imobj.set_data( data + np.random.random((100,1)) * 0.5 )
return line_simu, time_text, imobj
def forceAspect(ax,aspect=1):
im = ax.get_images()
extent = im[0].get_extent()
ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)
fig = plt.figure()
ax = plt.axes(xlim=(-15,15), ylim=(-110, 0) , aspect=1)
data = np.random.random((100,100)) - .5
imobj = ax.imshow( data , extent=[-15,15, -110, 0.0], origin='lower', cmap=plt.cm.gray, vmin=-2, vmax=2, alpha=.7, zorder=0, aspect=1)
line_simu, = ax.plot([], [],"r--", lw=2, markersize=4 , label = "Some curve" , zorder= 2 )
time_text = ax.text(-14.9, -108, '', zorder=10)
l = plt.legend(loc='lower right', prop={'size':8} )
l.set_zorder(200)
forceAspect(ax,aspect=1)
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=range( 50), interval=3000, blit=True)
plt.show()
Without animation, I can easily control the order of the different elements with set_zorder, but when the animation updates the image, this order is lost. I tried to set the zorder in the init function and again in the animate function, without success.
I am very thankful for any help on that matter.
To answer my own question: It seems that the order in witch the init() and animate() functions return objects controls the order in which they are displayed. Additionally those functions should return the legend object in order to include it in the animation.
Here is my corrected code:
#! /usr/bin/python
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import random
def init():
imobj.set_data(np.zeros((100, 100)))
line_simu.set_data([], [])
time_text.set_text('time = 0.0')
return imobj , line_simu, time_text, l
def animate(i):
global data
imobj.set_data( data + np.random.random((100,1)) * 0.5 )
imobj.set_zorder(0)
y_simu = np.linspace(-100,-10, 100)
x_simu = np.linspace(-10, 10, 100)
line_simu.set_data(x_simu, y_simu)
time_text.set_text('time = %.1f' % i )
return imobj , line_simu, time_text, l
def forceAspect(ax,aspect=1):
im = ax.get_images()
extent = im[0].get_extent()
ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)
fig = plt.figure()
ax = plt.axes(xlim=(-15,15), ylim=(-110, 0) , aspect=1)
data = np.random.random((100,100)) - .5
imobj = ax.imshow( data , extent=[-15,15, -110, 0.0], origin='lower', cmap=plt.cm.gray, vmin=-2, vmax=2, alpha=1.0, zorder=1, aspect=1)
line_simu, = ax.plot([], [],"r--", lw=2, markersize=4 , label = "Some curve" , zorder= 1 )
time_text = ax.text(-14.0, -108, '', zorder=10)
forceAspect(ax,aspect=1)
l = plt.legend(loc='lower right', prop={'size':8} )
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=range( 50), interval=500, blit=True)
plt.show()

Categories

Resources