当前位置: 首页 > news >正文

精品课程网站开发云南省建设厅网站发文

精品课程网站开发,云南省建设厅网站发文,阳江市网络问政首页,微信公众平台推广费用趋势#xff08;一#xff09;利用python绘制折线图 折线图#xff08; Line Chart#xff09;简介 折线图用于在连续间隔或时间跨度上显示定量数值#xff0c;最常用来显示趋势和关系#xff08;与其他折线组合起来#xff09;。折线图既能直观地显示数量随时间的变化…趋势一利用python绘制折线图 折线图 Line Chart简介 折线图用于在连续间隔或时间跨度上显示定量数值最常用来显示趋势和关系与其他折线组合起来。折线图既能直观地显示数量随时间的变化趋势也能展示两个变量的关系。 快速绘制 基于matplotlib import matplotlib.pyplot as plt import numpy as np# 自定义数据 values np.cumsum(np.random.randn(1000,1))# 绘制折线图 plt.plot(values) plt.show()基于seaborn import seaborn as sns import matplotlib.pyplot as plt import numpy as np# 自定义数据 values np.cumsum(np.random.randn(1000,1))# 绘制折线图 sns.lineplot(xnp.array(range(1, 1001)), yvalues.ravel()) # 使用 ravel() 将 values 转化为一维 plt.show()基于plotly import plotly.graph_objects as go import numpy as np# 自定义数据 values np.cumsum(np.random.randn(1000,1))# 绘制折线图 fig go.Figure(datago.Scatter(xlist(range(1, 1001)), yvalues.ravel(), modelines)) fig.show()基于pandas import numpy as np import matplotlib.pyplot as plt import pandas as pd# 自定义数据 values np.cumsum(np.random.randn(1000,1)) df pd.DataFrame(values, columns[Values])# 绘制折线图 df.plot() plt.show()定制多样化的折线图 自定义折线图一般是结合使用场景对相关参数进行修改并辅以其他的绘图知识。参数信息可以通过官网进行查看其他的绘图知识则更多来源于实战经验大家不妨将接下来的绘图作为一种学习经验以便于日后总结。 通过matplotlib绘制多样化的折线图 matplotlib主要利用plot绘制折线图可以通过matplotlib.pyplot.plot了解更多用法 修改参数 import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pdplt.rcParams[font.sans-serif] [SimHei] # 用来正常显示中文标签# 自定义数据 dfpd.DataFrame({x_values: range(1,11), y_values: np.random.randn(10) })# 初始化布局 fig plt.figure(figsize(12,3))# 自定义颜色 plt.subplot(1, 3, 1) plt.plot( x_values, y_values, datadf, colorskyblue) plt.title(自定义颜色)# 自定义透明度 plt.subplot(1, 3, 2) plt.plot( x_values, y_values, datadf, colorskyblue, alpha0.3) plt.title(自定义透明度)# 自定义线条 plt.subplot(1, 3, 3) plt.plot( x_values, y_values, datadf, linestyledashed, linewidth5) plt.title(自定义线条)plt.show()带注释的折线图 import matplotlib.pyplot as plt import numpy as np import pandas as pdplt.rcParams[font.sans-serif] [SimHei] # 用来正常显示中文标签# 自定义数据 dates []for date in range(1970,2023):dates.append(str(date))sample_size 2023-1970 variable np.random.normal(100,15,sample_size,)df pd.DataFrame({date: dates,value: variable})# 初始化布局 fig plt.figure(figsize(12,8))# 1-基本折线图 plt.subplot(2, 1, 1) plt.plot(df[date], df[value])# 轴标签 plt.xlabel(X-axis) plt.ylabel(Y-axis) plt.title(基本折线图)# 刻度 plt.xticks(rotation45)# 2-带注释的折线图 plt.subplot(2, 1, 2) plt.plot(df[date], df[value])# 轴标签 plt.xlabel(X-axis) plt.ylabel(Y-axis) plt.title(带注释的折线图)# 刻度 plt.xticks(rotation45)# 添加文本注释 plt.text(df[date].iloc[38], # x位置df[value].iloc[1], # y位置What a nice chart!, # 文本注释fontsize13,colorred)# 找到最大值索引 highest_index df[value].idxmax()# 最高值标记 plt.scatter(df[date].iloc[highest_index],df[value].iloc[highest_index],colorblue,markero, # 标记特殊的店s100,)# 计算均值 median_value df[value].median()# 添加均值线 plt.axhline(ymedian_value, colorgreen, linestyle--, labelReference Line (Median))fig.tight_layout() # 自动调整间距 plt.show()对数变换的折线图 import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator import numpy as np import pandas as pdplt.rcParams[font.sans-serif] [SimHei] # 用来正常显示中文标签# 自定义数据 x np.linspace(1, 10, 100) y np.exp(x) df pd.DataFrame({x: x, y: y})# 初始化布局 fig plt.figure(figsize(12,4))# 1-基本折线图 plt.subplot(1, 2, 1) plt.plot(df[x], df[y])# 轴标签 plt.xlabel(X-axis) plt.ylabel(Y-axis) plt.title(基本折线图)# 添加网格线 plt.grid(True, linestyle--, alpha0.6)# 2-对数转化折线图 plt.subplot(1, 2, 2) plt.plot(df[x], df[y])# y轴对数化 plt.yscale(log)# 轴标签 plt.xlabel(X-axis) plt.ylabel(Y-axis) plt.title(对数化的折线图)# 对数刻度的网格 y_major_locator MultipleLocator(3000) plt.gca().yaxis.set_major_locator(y_major_locator)# 添加网格线 plt.grid(True, linestyle--, alpha0.6)plt.show()双轴折线图 import matplotlib.pyplot as plt import numpy as np from datetime import datetime, timedelta from matplotlib import colorsplt.rcParams[font.sans-serif] [SimHei] # 用来正常显示中文标签rng np.random.default_rng(1234)date [datetime(2019, 1, 1) timedelta(i) for i in range(100)] temperature np.arange(100) ** 2.5 / 10000 rng.uniform(size100) price np.arange(120, 20, -1) ** 1.5 / 10 rng.uniform(size100)# 设置多子图 fig, axarr plt.subplots(2, 2, figsize(12, 8))# 1-基础的双轴折线图 ax1 axarr[0, 0] ax2 ax1.twinx() ax1.plot(date, temperature) ax2.plot(date, price) ax1.set_title(基础的双轴折线图)# 2-自定义颜色双轴 COLOR_TEMPERATURE #69b3a2 COLOR_PRICE #3399e6ax1 axarr[0, 1] ax2 ax1.twinx() ax1.plot(date, temperature, colorCOLOR_TEMPERATURE, lw3) ax2.plot(date, price, colorCOLOR_PRICE, lw4)ax1.set_xlabel(Date) ax1.set_ylabel(Temperature (Celsius °), colorCOLOR_TEMPERATURE, fontsize14) ax1.tick_params(axisy, labelcolorCOLOR_TEMPERATURE) ax2.set_ylabel(Price ($), colorCOLOR_PRICE, fontsize14) ax2.tick_params(axisy, labelcolorCOLOR_PRICE) ax1.set_title(自定义颜色双轴)# 3-折线与条形图组合 ax1 axarr[1, 0] ax2 ax1.twinx() ax1.bar(date, temperature, colorCOLOR_TEMPERATURE, edgecolorblack, alpha0.4, width1.0) ax2.plot(date, price, colorCOLOR_PRICE, lw4)ax1.set_xlabel(Date) ax1.set_ylabel(Temperature (Celsius °), colorCOLOR_TEMPERATURE, fontsize14) ax1.tick_params(axisy, labelcolorCOLOR_TEMPERATURE)ax2.set_ylabel(Price ($), colorCOLOR_PRICE, fontsize14) ax2.tick_params(axisy, labelcolorCOLOR_PRICE)fig.autofmt_xdate() ax1.set_title(折线与条形图组合)# 4-自定义组合图样式 color list(colors.to_rgba(COLOR_TEMPERATURE)) color[3] 0.4ax1 axarr[1, 1] ax2 ax1.twinx() ax1.bar(date, temperature, colorcolor, edgecolorblack, width1.0) ax2.plot(date, price, colorCOLOR_PRICE, lw4)ax1.set_xlabel(Date) ax1.set_ylabel(Temperature (Celsius °), colorCOLOR_TEMPERATURE, fontsize14) ax1.tick_params(axisy, labelcolorCOLOR_TEMPERATURE)ax2.set_ylabel(Price ($), colorCOLOR_PRICE, fontsize14) ax2.tick_params(axisy, labelcolorCOLOR_PRICE)fig.autofmt_xdate() ax1.set_title(自定义组合图样式)fig.tight_layout() # 自动调整间距 plt.show()多个折线图 import matplotlib.pyplot as plt import numpy as np from datetime import datetime, timedelta from matplotlib import colors import matplotlib.gridspec as gridspecplt.rcParams[font.sans-serif] [SimHei] # 用来正常显示中文标签# 创建 2x3 的大布局 fig plt.figure(figsize(18, 8)) gs gridspec.GridSpec(2, 3, figurefig) # 获得每个子图的位置 ax1 fig.add_subplot(gs[0, 0]) ax2 fig.add_subplot(gs[0, 1]) ax3 fig.add_subplot(gs[0, 2]) # ax4 fig.add_subplot(gs[1, 0]) # ax5 fig.add_subplot(gs[1, 1]) ax6 fig.add_subplot(gs[1, 2])# 1-基础的多折线图 dfpd.DataFrame({x_values: range(1,11), y1_values: np.random.randn(10), y2_values: np.random.randn(10)range(1,11), y3_values: np.random.randn(10)range(11,21) })ax1.plot( x_values, y1_values, datadf, markero, markerfacecolorblue, markersize12, colorskyblue, linewidth4) ax1.plot( x_values, y2_values, datadf, marker, colorolive, linewidth2) ax1.plot( x_values, y3_values, datadf, marker, colorolive, linewidth2, linestyledashed, labeltoto) ax1.legend() ax1.set_title(基础的多折线图)# 2-高亮显示一组 dfpd.DataFrame({x: range(1,11), y1: np.random.randn(10), y2: np.random.randn(10)range(1,11), y3: np.random.randn(10)range(11,21), y4: np.random.randn(10)range(6,16), y5: np.random.randn(10)range(4,14)(0,0,0,0,0,0,0,-3,-8,-6), y6: np.random.randn(10)range(2,12), y7: np.random.randn(10)range(5,15), y8: np.random.randn(10)range(4,14) })for column in df.drop(x, axis1):ax2.plot(df[x], df[column], marker, colorgrey, linewidth1, alpha0.4) ax2.plot(df[x], df[y5], marker, colororange, linewidth4, alpha0.7) # 高亮y5 ax2.set_xlim(0,12) # 增加注释 num0 for i in df.values[9][1:]:num1namelist(df)[num]if name ! y5:ax2.text(10.2, i, name, horizontalalignmentleft, sizesmall, colorgrey)else:ax2.text(10.2, i, Mr Orange, horizontalalignmentleft, sizesmall, colororange) # 高亮组的文本注释 ax2.set_title(高亮显示一组)# 3-多折线模式Spaghetti Plot dfpd.DataFrame({x: range(1,11), y1: np.random.randn(10), y2: np.random.randn(10)range(1,11), y3: np.random.randn(10)range(11,21), y4: np.random.randn(10)range(6,16), y5: np.random.randn(10)range(4,14)(0,0,0,0,0,0,0,-3,-8,-6), y6: np.random.randn(10)range(2,12), y7: np.random.randn(10)range(5,15), y8: np.random.randn(10)range(4,14), y9: np.random.randn(10)range(4,14), y10: np.random.randn(10)range(2,12) })palette plt.get_cmap(Set1) num0 for column in df.drop(x, axis1):num1ax3.plot(df[x], df[column], marker, colorpalette(num), linewidth1, alpha0.9, labelcolumn)ax3.legend(loc2, ncol2) ax3.set_title(多折线模式Spaghetti Plot)# 4-多折线小图 dfpd.DataFrame({x: range(1,11), y1: np.random.randn(10), y2: np.random.randn(10)range(1,11), y3: np.random.randn(10)range(11,21), y4: np.random.randn(10)range(6,16), y5: np.random.randn(10)range(4,14)(0,0,0,0,0,0,0,-3,-8,-6), y6: np.random.randn(10)range(2,12), y7: np.random.randn(10)range(5,15), y8: np.random.randn(10)range(4,14), y9: np.random.randn(10)range(4,14) }) # 在第一行第一列的位置创建3*3的子布局 ax4 gridspec.GridSpecFromSubplotSpec(3, 3, subplot_specgs[1, 0]) # 在 3x3 的小布局中添加子图 axes [] for i in range(3):for j in range(3):ax fig.add_subplot(ax4[i, j])axes.append(ax) # 将子图句柄添加到列表中 num 0 for column in df.drop(x, axis1):num 1ax axes[num - 1]ax.plot(df[x], df[column], marker, colorpalette(num), linewidth1.9, alpha0.9, labelcolumn)ax.set_xlim(0,10)ax.set_ylim(-2,22)# 如果当前子图不在最左边就不显示y轴的刻度标签if num not in [1,4,7] :ax.tick_params(labelleftFalse)# 如果当前子图不在最下边就不显示x轴的刻度标签if num not in [7,8,9] :ax.tick_params(labelbottomFalse)ax.annotate(column, xy(0, 1), xycoordsaxes fraction, fontsize12, fontweight0, colorpalette(num),xytext(5, -5), textcoordsoffset points, haleft, vatop)axes[1].set_title(多折线小图) # 通过设置3*3图的第二个子图的标题替代2*3图中的第4个图的子标题# 5-多折线小图细节处理 dfpd.DataFrame({x: range(1,11), y1: np.random.randn(10), y2: np.random.randn(10)range(1,11), y3: np.random.randn(10)range(11,21), y4: np.random.randn(10)range(6,16), y5: np.random.randn(10)range(4,14)(0,0,0,0,0,0,0,-3,-8,-6), y6: np.random.randn(10)range(2,12), y7: np.random.randn(10)range(5,15), y8: np.random.randn(10)range(4,14), y9: np.random.randn(10)range(4,14) }) # 在第一行第一列的位置创建3*3的子布局 ax5 gridspec.GridSpecFromSubplotSpec(3, 3, subplot_specgs[1, 1]) # 在 3x3 的小布局中添加子图 axes [] for i in range(3):for j in range(3):ax fig.add_subplot(ax5[i, j])axes.append(ax) # 将子图句柄添加到列表中 num0 for column in df.drop(x, axis1):num1ax axes[num - 1]for v in df.drop(x, axis1):ax.plot(df[x], df[v], marker, colorgrey, linewidth0.6, alpha0.3)ax.plot(df[x], df[column], marker, colorpalette(num), linewidth2.4, alpha0.9, labelcolumn)ax.set_xlim(0,10)ax.set_ylim(-2,22)# 如果当前子图不在最左边就不显示y轴的刻度标签if num not in [1,4,7] :ax.tick_params(labelleftFalse)# 如果当前子图不在最下边就不显示x轴的刻度标签if num not in [7,8,9] :ax.tick_params(labelbottomFalse)ax.annotate(column, xy(0, 1), xycoordsaxes fraction, fontsize12, fontweight0, colorpalette(num),xytext(5, -5), textcoordsoffset points, haleft, vatop)axes[1].set_title(多折线小图细节处理) # 通过设置3*3图的第二个子图的标题替代2*3图中的第5个图的子标题# 6-带区域填充的多折线图 time np.arange(12) income np.array([5, 9, 6, 6, 10, 7, 6, 4, 4, 5, 6, 4]) expenses np.array([6, 6, 8, 3, 6, 9, 7, 8, 6, 6, 4, 8])ax6.plot(time, income, colorgreen) ax6.plot(time, expenses, colorred)# 当income expenses填充绿色 ax6.fill_between(time, income, expenses, where(income expenses), interpolateTrue, colorgreen, alpha0.25, labelPositive )# 当income expenses填充红色 ax6.fill_between(time, income, expenses, where(income expenses), interpolateTrue, colorred, alpha0.25,labelNegative )ax6.set_title(带区域填充的多折线图) ax6.legend()plt.tight_layout() # 自动调整间距 plt.show()绘制时间序列图 import matplotlib.pyplot as plt import pandas as pd import matplotlib.dates as mdates# 导入数据 data pd.read_csv(https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered.csv, delim_whitespaceTrue )# 日期格式 data[date] pd.to_datetime(data[date])date data[date] value data[value]# 绘制时间序列图 fig, ax plt.subplots(figsize(8, 6))# 设置6个月间隔为一刻度 half_year_locator mdates.MonthLocator(interval6) # 半年刻度 monthly_locator mdates.MonthLocator() # 每月子刻度 year_month_formatter mdates.DateFormatter(%Y-%m) # 格式化日期yyyy-MMax.xaxis.set_major_locator(half_year_locator) ax.xaxis.set_minor_locator(monthly_locator) ax.xaxis.set_major_formatter(year_month_formatter)ax.plot(date, value)fig.autofmt_xdate() # 自动旋转轴标签通过plotly绘制多样化的折线图 import plotly.graph_objects as go import numpy as np import pandas as pd# 自定义数据dates [] start 1990 end 2022 for date in range(start,end):dates.append(str(date))# 生成随机序列并计算累计和来生成随机漫步1、2、3 random_steps np.random.choice([-1, 1], sizeend-start, p[0.5, 0.5]) random_walk1 np.cumsum(random_steps)random_steps np.random.choice([-1, 1], sizeend-start, p[0.5, 0.5]) random_walk2 np.cumsum(random_steps)random_steps np.random.choice([-1, 1], sizeend-start, p[0.5, 0.5]) random_walk3 np.cumsum(random_steps)# 具有三个随机漫步的数据 df pd.DataFrame({date: dates,value1: random_walk1,value2: random_walk2,value3: random_walk3,})fig go.Figure()# 自定义变量1 fig.add_trace(go.Scatter(xdf[date],ydf[value1],modelinesmarkers, # 点线连接样式nameLine1,markerdict(symbolsquare, size10, colorred), linedict(colorblue, width5) ))# 自定义变量2 fig.add_trace(go.Scatter(xdf[date], ydf[value2], modelinesmarkers, nameLine2, markerdict(symbolcircle, size7, colorpurple), linedict(colororange, width8) ))# 自定义变量3 fig.add_trace(go.Scatter(xdf[date], ydf[value3], modelinesmarkers, nameLine3,markerdict(symboldiamond, size15, coloryellow), linedict(colorgreen, width4) ))# 自定义布局 fig.update_layout(titleCustomized Line Chart,xaxis_titleX Axis Label, yaxis_titleY Axis Label,xaxis_tickangle45, showlegendTrue, plot_bgcolorwhite, paper_bgcolorlightblue, ) 通过pandas绘制多样化的折线图 修改参数 import pandas as pd import matplotlib.pyplot as plt# 导入数据 url https://raw.githubusercontent.com/holtzy/The-Python-Graph-Gallery/master/static/data/gapminderData.csv df pd.read_csv(url) df_france df[df[country]France]# 绘制折线图 ax df_france.plot(xyear,ylifeExp,gridTrue,linestyle--,alpha0.5,colorpurple,linewidth2.0, markerd, markersize8, markerfacecolororange, labelFrance)# 标题 ax.set_title(Evolution of \nthe life expectancy in France,weightbold) # 轴标签 ax.set_ylabel(Life Expectancy) ax.set_xlabel(Time (in year))plt.show()多变量折线图 import pandas as pd import random, numpy as np import matplotlib.pyplot as plt# 自定义数据 num_time_points 100 time_values np.arange(num_time_points)temperature np.random.uniform(200, 400, num_time_points) pressure np.random.uniform(500, 700, num_time_points) humidity np.random.uniform(800, 1000, num_time_points) data {Time: time_values,Temperature: temperature,Pressure: pressure,Humidity: humidity } df pd.DataFrame(data)# 绘制多变量折线图 df.plot(xTime,kindline, gridTrue, ) plt.legend(locupper right,bbox_to_anchor(1.35, 1), ) plt.show()分组折线图 import pandas as pd import random, numpy as np import matplotlib.pyplot as plt# 自定义数据 num_data_points_per_country 20# 设置多个国家的温度 france_temperatures np.random.uniform(10, 20, num_data_points_per_country) germany_temperatures np.random.uniform(0, 10, num_data_points_per_country) italy_temperatures np.random.uniform(25, 30, num_data_points_per_country) # 对应的国家数据 countries [France, Germany, Italy] country_labels np.repeat(countries, num_data_points_per_country)# 时间数据 time_values np.tile(np.arange(num_data_points_per_country), len(countries))data {Country: country_labels,Temperature: np.concatenate([france_temperatures, germany_temperatures, italy_temperatures]),Time: time_values }df pd.DataFrame(data)# 绘制折线图 for name, group in df.groupby(Country):plt.plot(group[Time], group[Temperature], labelname)# 设置图表的标题和坐标轴标签并显示图例 plt.title(Temperature Trend over Time by Country) plt.xlabel(Time) plt.ylabel(Temperature) plt.legend(bbox_to_anchor(1.05, 1), locupper left)# 显示图表 plt.show()总结 以上通过matplotlib、seaborn、plotly和pandas快速绘制折线图。并通过修改参数或者辅以其他绘图知识自定义各种各样的折线图来适应相关使用场景。 共勉
http://www.yingshimen.cn/news/48009/

相关文章:

  • 网站设计师认证培训网络营销是啥意思
  • 制作购物网站教程legenda wordpress
  • 用商标做网站名字wordpress添加统计代码
  • 网站网页文案怎么写制作照片
  • 达建网站威海 网站开发
  • 合肥做网站工作室德州 网站建设
  • 亚马逊海外网站甜品网页设计模板html
  • 少儿编程自学网站东莞厚街做网站
  • 网站下拉菜单html做多大家装公司排名前十强
  • 天津有哪些好的做网站公司网站源码建站
  • 和平网站建设sz住房和城乡建设部网站
  • 网站建设实训个人总结1000字怎么建立一个网站网址
  • 网站营销方法东莞企业黄页资料
  • 招聘网站可以做两份简历吗网络工程师 网站建设
  • 成都武侯区网站建设简单静态网站模板
  • 邯郸大网站青岛网站优化联系方式
  • 企业网站建设动图深圳网站制作易捷网络
  • 佛山市建设局网站管理咨询公司项目运作流程图
  • 上海软件培训网站建设网站ip和pv
  • 黑彩网站充值就给你做单子黑豹站群系统
  • 网站外链建设分析网页设计基础知识总结
  • 12306网站谁做的学做网站是什么专业
  • 网站点击率高深圳高端商场排名
  • 向客户介绍网站建设的话本html代码入门
  • 好123设为主页官网优化网站公司
  • 网站空间价格专业企业网站制作怎么做
  • 三星单片机开发网站wordpress添加附件下载
  • 星裕建设网站做二手网站有哪些问题
  • 做网站要几天大连网站建设找哪家好
  • 买布自己做网站衣服的wordpress主题模版开发