欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

spyder中绘图无法显示负号_matlibplot+seaborn绘图风格交叉使用

发布时间:2025/3/21 编程问答 52 豆豆
生活随笔 收集整理的这篇文章主要介绍了 spyder中绘图无法显示负号_matlibplot+seaborn绘图风格交叉使用 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

matlibplot+seaborn绘图风格交叉使用

遇到问题:想要图一的图案,但是想要seaborn中默认的风格绘制

图一

一开始的想法是seaborn既然升级版matlibplot,应该支持直接修改plt.plot==>sns.barplot ,但实际上是不支持的。

# coding:utf-8 from pandas import Series,DataFrame from numpy.random import randn import numpy as np import matplotlib.pyplot as plt from pylab import mpl import seaborn as sns sns.set_style("whitegrid") plt.rc("font",family="SimHei",size="16") #用于解决中文显示不了的问题 sns.set_style("whitegrid") plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文字体设置-黑体 plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 sns.set(font='SimHei') # 解决Seaborn中文显示问题#创建一个画板 fig=plt.figure(figsize=(8,6))#为画板划分多个Axes ax = plt.subplot(111) #假如设置为221,则表示创建两行两列也就是4个子画板,ax为第一个子画板#数据准备 stock_type_list=[[396, 384], [351, 429], [0, 780], [368, 412], [0, 780], [167, 613], [390, 390], [4, 776], [332, 448], [399, 381], [25, 755], [265, 515]]#y轴数据 ya = np.array([i[0] for i in stock_type_list[::3]]) # 股价差跌 yb = np.array([i[1] for i in stock_type_list[::3]])#柱状图的宽度 width = 0.3 #x轴数据 x_bar = np.arange(4)#绘制柱状图 rects1 = sns.barplot(x_bar-width/2,ya,label='跌') rects2 = sns.barplot(x_bar+width/2,yb,label='涨',)#为柱状图添加高度值(不能使用因为sns.plot中不是iteration) # for rect in rects1: # x1 = rect.get_x() # height1 = rect.get_height() # ax.text(x1+0.2,1.01*height1,str(height1)) # # print(x,height) # for rect in rects2: # x2 = rect.get_x() # height2 = rect.get_height() # ax.text(x2+0.2,1.01*height2,str(height2))#设置x轴的刻度 ax.set_xticks(x_bar) ax.set_xticklabels(['后1天股价差','后5天股价差','后20天股价差','后60天股价差'])#设置y轴的刻标注 ax.set_ylabel("回购数量(单位:次数)") ax.set_xlabel("回购后影响天数")#是否显示网格 # ax.grid(True)#拉伸y轴 # ax.set_ylim(0,28)#设置标题 ax.set_title("回购后的股价差涨跌幅统计")plt.legend(loc='lower right')#显示图表 plt.show()fig.savefig('回购后股价差.png')

图二

出来结果图二是柱状图混乱,没有显示两个柱状图。

第二次:是创建一个dataframe,和使用seaborn绘制折线想法一样,直接扔一堆data到sns.lineplot(data=DataFrame)即可

# 使用seaborn绘制多柱状图 ''' 使用seaborn绘制双柱状图不可行的原因:sns.barplot的api接口太高级,sns的思想是,你给我数据,我来帮你区分怎么样切割数据 例如:seaborn.barplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, estimator=<function mean at 0x10a2a03b0>, ci=95, n_boot=1000, units=None, seed=None, orient=None, color=None, palette=None, saturation=0.75, errcolor='.26', errwidth=None, capsize=None, dodge=True, ax=None, **kwargs) 直接给定dataframe中的x,y,hue来切割,data=DataFrame,直接绘制会无法识别,而发生重叠但是绘制折线图是可以:sns.lineplot折线可以的原因是折线本身可以发生重叠。 '''price_dict={ # 'index':['后1天股价差','后5天股价差','后20天股价差','后60天股价差'],'股价跌':[396,368,390,399],'股价涨':[384,412,390,381],}price_diff_df=pd.DataFrame(data=price_dict ,index=['后1天股价差','后5天股价差','后20天股价差','后60天股价差'],)price_diff_dfprice_sea_da=[price_diff_df["股价跌"],price_diff_df["股价涨"]]fig=plt.figure(figsize=(8,4)) ax = plt.subplot(111)ax=sns.barplot(data=price_sea_da)ax.set_ylabel("回购后n天平均股价变化") # 比如回购发生后几天内的平均股价 ax.set_xlabel("占总股本比例(单位:%)增长排序")#设置x轴的刻度 ax.set_title("回购后n天平均股价变化") # ax.set_xticklabels(price_sort_df['占总股本比例'].tolist())plt.show() # fig.savefig('回购后n天占总股本比例--平均股价变化.png')

第三次:可以在绘制matlibplot的基础上,修改到seaborn的风格

# coding:utf-8 from pandas import Series,DataFrame from numpy.random import randn import numpy as np import matplotlib.pyplot as plt from pylab import mpl import seaborn as sns # sns.set_style("whitegrid") plt.rc("font",family="SimHei",size="16") #用于解决中文显示不了的问题 # sns.set_style("whitegrid") plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文字体设置-黑体 plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 sns.set(font='SimHei') # 解决Seaborn中文显示问题 % matplotlib inline#再论柱状图 #创建一个画板 print("可使用的风格",plt.style.available) fig=plt.figure(figsize=(8,6)) plt.style.use('tableau-colorblind10') # 这种风格可以使用中文字体,使用seaborn默认交叉使用matlibplot会不支持中文,算一个bug?#为画板划分多个Axes ax = plt.subplot(111) #假如设置为221,则表示创建两行两列也就是4个子画板,ax为第一个子画板#数据准备 stock_type_list=[[396, 384], [351, 429], [0, 780], [368, 412], [0, 780], [167, 613], [390, 390], [4, 776], [332, 448], [399, 381], [25, 755], [265, 515]]#y轴数据 ya = np.array([i[0] for i in stock_type_list[1::3]]) # 股价差跌 yb = np.array([i[1] for i in stock_type_list[1::3]])#柱状图的宽度 width = 0.3 #x轴数据 x_bar = np.arange(4)#绘制柱状图 rects1 = ax.bar(x_bar-width/2,ya,width=width,label='跌',color='darkseagreen') rects2 = ax.bar(x_bar+width/2,yb,width=width,label='涨',color='olive')#为柱状图添加高度值 for rect in rects1:x1 = rect.get_x()height1 = rect.get_height()ax.text(x1+0.1,1.01*height1,str(height1)) # print(x,height) for rect in rects2:x2 = rect.get_x()height2 = rect.get_height()ax.text(x2+0.1,1.01*height2,str(height2))#设置x轴的刻度 ax.set_xticks(x_bar) ax.set_xticklabels([u'后1天平均股价','后5天平均股价','后20天平均股价','后60天平均股价'])#设置y轴的刻标注 ax.set_ylabel("回购数量(单位:次数)") ax.set_xlabel("回购后影响天数") #是否显示网格 # ax.grid(True) #拉伸y轴 # ax.set_ylim(0,28) #设置标题 ax.set_title("回购后的平均股价涨跌幅统计") plt.legend(loc='lower right') #显示图表 plt.show() # fig.savefig('回购后平均股价.png')

图三

总结

以上是生活随笔为你收集整理的spyder中绘图无法显示负号_matlibplot+seaborn绘图风格交叉使用的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。