6.1 坐标轴概述
在绘制图表的过程中,marplotlib会根据所终園表的类形洪定是否使用坐标系,或者显示哪种类型的坐标系。例如,饼图无坐标系,雷达劉需使用板坐标系,折线園雷使用直魚璺船系等。其中,直角坐标系经常被使用。marplotlib 中的直角坐标系由两条水平坐标轴,两条垂直坐标轴以及围成的绘图区城构成,以限制图形显示的区城,其左侧和下方的坐标轴 (叫做Y轴和X轴)经常被使用,其他坐标轴很少被使用。
6.2 向任位置添加坐标轴
marplotlib支特向画布的任意位置添加自定义大小的坐标系统,同时显示坐标轴,而不再受规划区城的限制。pyplot機块可以使用axes()函数创建一个人Axes类的对象。并将Axes类的对象添加到当前画布中。axes()函数的语法格式如下:
axes (arg=None projection=None, polar=False, aspect, frame_on, **kwargs)
案例一:
1.代码如下:
import matplotlib.pyplot as plt
ax = plt.axes((0.2, 0.5, 0.3, 0.3))
ax.plot([1, 2, 3, 4, 5])
ax2 = plt.axes((0.6, 0.4, 0.2, 0.2))
ax2.plot([1, 2, 3, 4, 5])
plt.title("2020080603052")
plt.show()
运行代码结果如下:

6.3 定制刻度
6.3.1 定制刻度的位置和格式
在matplotlib中,刻度线分为主刻度线和次刻度线,次刻度线默认是隐藏matplotlib.ticker模块中提供了两个类:Locator 和Formatter,分別代表刻度定位器和刻度格式器,用于指定刻度线的位置和刻度标签的格式。
6.3.2 定制刻度的样式
在matplotlib 中,坐标轴的刻度有着固定的样式,例如,刻度线的方向是朝外的,刻度
线的颜色是黑色等。pyplot 中可以使用tick_paramas()函数定制刻度的样式tick_parama()函数的语法格式如下:
tick_params(axis='both',**kwargs)
案例二:
1.代码如下:
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib.dates import DateFormatter, HourLocator
ax = plt.gca()
hour_loc = HourLocator(interval=2)
date_fmt = DateFormatter('%Y/%m/%d')
ax.xaxis.set_major_locator(hour_loc)
ax.xaxis.set_major_formatter(date_fmt)
plt.tick_params(labelrotation=30)
运行代码,结果如下:

案例三:深圳市24小时的平均风速
数据如下:
时间风速00:00702:00904:001106:001408:00810:001512:002214:001116:001018:001120:001324:008运行代码如下:
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, HourLocator
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
dates = ['201910240','2019102402','2019102404','2019102406',
'2019102408','2019102410','2019102412', '2019102414',
'2019102416','2019102418','2019102420','2019102422','201910250' ]
x_date = [datetime.strptime(d, '%Y%m%d%H') for d in dates]
y_data = np.array([7, 9, 11, 14, 8, 15, 22, 11, 10, 11, 11, 13, 8])
fig = plt.figure()
ax = fig.add_axes((0.0, 0.0, 1.0, 1.0))
ax.plot(x_date, y_data, '->', ms=8, mfc='#FF9900')
ax.set_title(' 深圳市24小时的平均风速 2020080603052')
ax.set_xlabel('时间(h)')
ax.set_ylabel('平均风速(km/h)')
date_fmt = DateFormatter('%H:%M')
ax.xaxis.set_major_formatter(date_fmt)
ax.xaxis.set_major_locator(HourLocator(interval=2))
ax.tick_params(direction='in', length=6, width=2, labelsize=12)
ax.xaxis.set_tick_params(labelrotation=45)
plt.show()
运行代码,结果如下:

6.4 隐藏轴脊
案例四:隐藏全部轴脊
代码如下:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpathes
polygon = mpathes.RegularPolygon((0.5, 0.5), 6, 0.2, color='g')
ax = plt.axes((0.3, 0.3, 0.5, 0.5))
ax.add_patch(polygon)
ax.axis('off')
plt.title("2020080603052")
plt.show()
运行代码,结果如下:

案例五:隐藏部分轴脊
代码如下:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpathes
xy = np.array([0.5,0.5])
polygon = mpathes.RegularPolygon(xy, 5, 0.2,color='y')
ax = plt.axes((0.3, 0.3, 0.5, 0.5))
ax.add_patch(polygon)
ax.spines['top'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
plt.title("2020080603052")
plt.show()
运行代码,结果如下:

运行代码如下:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpathes
xy = np.array([0.5,0.5])
polygon = mpathes.RegularPolygon(xy, 5, 0.2,color='y')
ax = plt.axes((0.3, 0.3, 0.5, 0.5))
ax.add_patch(polygon)
ax.spines['top'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.yaxis.set_ticks_position('none')
ax.set_yticklabels([])
plt.title("2020080603052")
plt.show()
运行代码,结果如下:

案例六:深圳市24小时的平均风速
代码如下:
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, HourLocator
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
dates = ['201910240','2019102402','2019102404','2019102406',
'2019102408','2019102410','2019102412', '2019102414',
'2019102416','2019102418','2019102420','2019102422','201910250' ]
x_date = [datetime.strptime(d, '%Y%m%d%H') for d in dates]
y_data = np.array([7, 9, 11, 14, 8, 15, 22, 11, 10, 11, 11, 13, 8])
fig = plt.figure()
ax = fig.add_axes((0.0, 0.0, 1.0, 1.0))
ax.plot(x_date, y_data, '->', ms=8, mfc='#FF9900')
ax.set_title(' 深圳市24小时的平均风速 2020080603052')
ax.set_xlabel('时间(h)')
ax.set_ylabel('平均风速(km/h)')
date_fmt = DateFormatter('%H:%M')
ax.xaxis.set_major_formatter(date_fmt)
ax.xaxis.set_major_locator(HourLocator(interval=2))
ax.tick_params(direction='in', length=6, width=2, labelsize=12)
ax.xaxis.set_tick_params(labelrotation=45)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
plt.show()
运行代码,结果如下:

6.5 移动轴脊
案例七:移动轴脊的位置:
代码如下:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpathes
xy = np.array([0.5,0.5])
polygon = mpathes.RegularPolygon(xy, 5, 0.2,color='y')
ax = plt.axes((0.3, 0.3, 0.5, 0.5))
ax.add_patch(polygon)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data', 0.5))
ax.spines['bottom'].set_position(('data', 0.5))
plt.title("2020080603052")
plt.show()
运行代码,结果如下:

案例八:正弦与余弦曲线
代码如下:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
x_data = np.linspace(-2 * np.pi, 2 * np.pi, 100)
y_one = np.sin(x_data)
y_two = np.cos(x_data)
fig = plt.figure()
ax = fig.add_axes((0.2, 0.2, 0.7, 0.7))
ax.plot(x_data, y_one, label='正弦曲线 ')
ax.plot(x_data, y_two, label='余弦曲线 ')
ax.legend()
ax.set_xlim(-2 * np.pi, 2 * np.pi)
ax.set_xticks([-2 * np.pi, -3 * np.pi / 2, -1 * np.pi, -1 * np.pi / 2,
0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi])
ax.set_xticklabels(['$-2\pi$', '$-3\pi/2$', '$-\pi$', '$-\pi/2$ ', '$0$',
'$\pi/2$', '$\pi$', '$3\pi/2$', '$2\pi$'])
ax.set_yticks([-1.0, -0.5, 0.0, 0.5, 1.0])
ax.set_yticklabels([-1.0, -0.5, 0.0, 0.5, 1.0])
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))
plt.title("2020080603052")
plt.show()
运行代码,结果如下:

Original: https://blog.csdn.net/weixin_55680181/article/details/123952267
Author: 张荣博2003
Title: Python数据可视化第六节(坐标轴的定制)
相关阅读
Title: pandas将df保存为excel,如何避免长数据序号被保存为科学计数法?解答各种坑
使用pandas处理包含产品序号的数据,序号是一串长的数字符号,遇到一系列科学技术法相关的问题。查阅了针对这个问题的一些已有解答,发现不能完全解决问题,也没有解释清楚问题出现的原因,所以举个简单的案例,彻底说明白怎么避免这个问题。
先放最终解决方案:
#显示不采用科学计数法
import numpy as np
np.set_printoptions(suppress=True)
pd.set_option('display.float_format', lambda x: '%.0f' % x)
#转excel不采用科学计数法
df['id'] = df['id'].astype(np.int64).astype(str)
df.to_excel('try.xlsx')
1.问题描述
结合一个小示例,了解可能出现的问题、原因以及上述解决方案可以解决的原因。
[En]
Combine a small example to see the possible problems, causes, and why the above solution can be solved.
首先,以这一串id为例:
x = [7030834394457750.0,7030834394457750.0,7030834394457750.0]
在这一过程中可能遇到的问题包括:
[En]
Problems that may be encountered in the process include:
问题1: pandas输出的df.head()等,长数字序号会被转换为科学计数,比如:

问题2: pandas将dataframe输出为excel时,excel中的数据也会以科学计数保存

2. 解决方案
问题1: pandas输出的df.head()等,长数字序号会被转换为科学计数
可以通过设置numpy的数据展示格式解决,在输出df前先运行以下代码:
import numpy as np
np.set_printoptions(suppress=True)
pd.set_option('display.float_format', lambda x: '%.0f' % x) #不采用科学计数法,不要小数点
再照常输出df:
bingo!

问题2: pandas将dataframe输出为excel时,excel中的数据也会以科学计数保存
为了回答这个问题,人们挖了很多洞。以下是几个例子:
[En]
Many holes have been dug to answer this question. Here are a few examples:
无效方案一:不需要处理,excel中的数据只是被转为了科学计数表达,只要转为数字格式就能复原
- 如果数字序号非常长的话,科学技术的小数点是保留不到那么多位的,这会导致数据精度丧失,对id这样的序号来说尤其不可取,比如对一串特别长的数字:
x = [7030834394457754405703083439703083439.0,7030834394457759800703083439703083439.0,7030834394457754409703083439703083439.0]
将其直接保存为科学计数,然后转换为:
[En]
After saving it directly into scientific counting and then converting it:

无效方案二:直接转成string再存储为excel
许多回答表示可以尝试’df[‘id’].astype(str)’再存储,但如果序号确实很长,这也会遇到问题。还是以上面为例,如果尝试以下代码:
df['id'].astype(str)
df.to_excel('try.xlsx')
得到的结果会是:

与前一次相比,它仍然没有解决问题。
[En]
Compared with the previous, it still does not solve the problem.
问题原因及方案
其实,出现这一问题的原因是,数据序号在原数据中的格式是float。可以注意到上面的小例子输入x的时候特意加了小数点:
import pandas as pd
x = [7030834394457750.0,7030834394457750.0,7030834394457750.0]
df = pd.DataFrame({'id':x})
df
如果不加小数点,默认识别成int的话,还有这个问题吗?
我们运行以下行,而不是更改数据显示格式:
[En]
Instead of changing the data display format, we run the following lines:
import pandas as pd
x = [7030834394457750,7030834394457750,7030834394457750]
df = pd.DataFrame({'id':x})
df
输出是:

但是,此时如果直接保存到excel,还是有科学计数的问题:

所以还需要再转换一次,先将长序号转为int,再将int转为string,这样就可以彻底解决问题二了。
综上所述,结合[显示格式设置]和[保存格式转换],问题1和问题2可以通过以下代码完全解决:
[En]
To sum up, with the combination of [display format setting] and [Save format conversion], problem 1 and problem 2 can be solved completely through the following code:
#显示不采用科学计数法
import numpy as np
np.set_printoptions(suppress=True)
pd.set_option('display.float_format', lambda x: '%.0f' % x)
#转excel不采用科学计数法
df['id'] = df['id'].astype(np.int64).astype(str)
df.to_excel('try.xlsx')
输出:

Excel:

Original: https://blog.csdn.net/liatan/article/details/124532529
Author: Liagogo
Title: pandas将df保存为excel,如何避免长数据序号被保存为科学计数法?解答各种坑
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/327964/
转载文章受原作者版权保护。转载请注明原作者出处!