日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

144个城市坐标Python程序

發布時間:2023/12/9 python 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 144个城市坐标Python程序 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 完整程序私信我,有償。
    • xlrd操作excel文件
      • 1.導入模塊:
      • 2.打開文件:
      • 3.獲取sheet:
      • 4.獲取sheet的匯總數據:
      • 5.單元格批量讀取:
      • 6.特定單元格讀取:
      • 7.(0,0)轉換A1:
      • 8.數據類型:
      • 9.讀取單元格中的日期
    • ndarray 與 list 互相轉換
    • 兩組點組算歐式距離
    • openpyxl操作excel文件
      • 1.新建工作表
      • 2.新建工作簿
      • 3.修改工作簿名稱,工作簿選項卡背景色
      • 4. 查看工作簿中所有工作表的名稱
      • 5.復制工作簿
      • 6.訪問單元格
      • 7.僅訪問單元格值
      • 8.保存至文件
      • 9.從文件加載
      • 10.寫入工作表
      • 11.更改時間格式
      • 12.合并/拆分單元格
      • 13.插入圖像
      • 14.隱藏列號和行號
      • 15.插入/刪除行或列,移動范圍單元格
      • 16.將Pandas Dataframes寫入工作簿
    • Python基礎語法
      • 1.enumerate() 函數
      • 2.List index()方法
    • Python turtle庫
      • 1.移動和繪制
      • 2.獲取海龜的狀態
      • 3.度量單位設置
      • 4.畫筆控制——繪圖狀態
      • 5.畫筆控制——顏色控制
      • 6.畫筆控制——填充
      • 7.畫筆控制——更多繪圖控制
      • 8.海龜狀態
    • [Python plotly_express庫](https://plotly.com/python/plotly-express/)
      • 1.散點圖
      • 2.折線圖
      • 3.import plotly.graph_objects as go

完整程序私信我,有償。

xlrd操作excel文件

參考博客1 參考博客2

1.導入模塊:

import xlrd

2.打開文件:

x1 = xlrd.open_workbook("data.xlsx")

3.獲取sheet:

  • 獲取所有sheet名字:x1.sheet_names()
  • 獲取sheet數量:x1.nsheets
  • 獲取所有sheet對象:x1.sheets()
  • 通過sheet名查找:x1.sheet_by_name("test”)
  • 通過索引查找:x1.sheet_by_index(3)
    例如:
print 'sheet_names:', x1.sheet_names() # 獲取所有sheet名字 print 'sheet_number:', x1.nsheets # 獲取sheet數量 print 'sheet_object:', x1.sheets() # 獲取所有sheet對象 print 'By_name:', x1.sheet_by_name("test") # 通過sheet名查找 print 'By_index:', x1.sheet_by_index(3) # 通過索引查找

結果:

sheet_names: [u' plan', u'team building', u'modile', u'test'] sheet_number: 4 sheet_object: [<xlrd.sheet.Sheet object at 0x10244c190>, <xlrd.sheet.Sheet object at 0x10244c150>, <xlrd.sheet.Sheet object at 0x10244c110>, <xlrd.sheet.Sheet object at 0x10244c290>] By_name: <xlrd.sheet.Sheet object at 0x10244c290> By_index: <xlrd.sheet.Sheet object at 0x10244c290>

4.獲取sheet的匯總數據:

  • 獲取sheet名:sheet1.name
  • 獲取總行數:sheet1.nrows
  • 獲取總列數:sheet1.ncols
    例子:
sheet1 = x1.sheet_by_name("plan") print "sheet name:", sheet1.name # get sheet name print "row num:", sheet1.nrows # get sheet all rows number print "col num:", sheet1.ncols # get sheet all columns number

結果:

sheet name: plan row num: 31 col num: 11

5.單元格批量讀取:

a)行操作:

  • sheet1.row_values(0) # 獲取第一行所有內容,合并單元格,首行顯示值,其它為空。
  • sheet1.row(0)   # 獲取單元格值類型和內容
  • sheet1.row_types(0) # 獲取單元格數據類型
sheet1 = x1.sheet_by_name("plan")# 單元格批量讀取 print sheet1.row_values(0) # 獲取第一行所有內容,合并單元格,首行顯示值,其它為空。 print sheet1.row(0) # 獲取單元格值類型和內容 print sheet1.row_types(0) # 獲取單元格數據類型 [u'learning plan', u'', u'', u'', u'', u'', u'', u'', 123.0, 42916.0, 0] [text:u'learning plan', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', number:123.0, xldate:42916.0, bool:0] array('B', [1, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4])

b) 表操作

  • sheet1.row_values(0, 6, 10) # 取第1行,第6~10列(不含第10列)
  • sheet1.col_values(0, 0, 5) # 取第1列,第0~5行(不含第5行)
  • sheet1.row_slice(2, 0, 2) # 獲取第3行0~1列的單位格值類型和內容
  • sheet1.row_types(1, 0, 2) # 獲取第2行0~1列的數據類型
sheet1 = x1.sheet_by_name("plan")# 列操作 print sheet1.row_values(0, 6, 10) # 取第1行,第6~10列(不含第10表) print sheet1.col_values(0, 0, 5) # 取第1列,第0~5行(不含第5行) print sheet1.row_slice(2, 0, 2) # 獲取第3行0~1列的單位格值類型和內容 print sheet1.row_types(1, 0, 2) # 獲取第2行0~1列的數據類型 [u'', u'', 123.0, 42916.0] [u'learning plan', u'\u7f16\u53f7', 1.0, 2.0, 3.0] [number:1.0, text:u'\u7ba1\u7406\u5b66\u4e60'] array('B', [1, 1])

6.特定單元格讀取:

a) 獲取單元格值:
sheet1.cell_value(1,0).encode(‘utf-8’)

  • sheet1.cell_value(1, 2)
  • sheet1.cell(1, 2).value
  • sheet1.row(1)[2].value
    b) 獲取單元格類型:
  • sheet1.cell(1, 2).ctype
  • sheet1.cell_type(1, 2)
  • sheet1.row(1)[2].ctype

7.(0,0)轉換A1:

  • xlrd.cellname(0, 0) # (0,0)轉換成A1
  • xlrd.cellnameabs(0, 0) # (0,0)轉換成$A$1
  • xlrd.colname(30) # 把列由數字轉換為字母表示
# (0,0)轉換成A1 print xlrd.cellname(0, 0) # (0,0)轉換成A1 print xlrd.cellnameabs(0, 0) # (0,0)轉換成$A$1 print xlrd.colname(30) # 把列由數字轉換為字母表示 A1 $A$1 AE

8.數據類型:

  • 空:0
  • 字符串:1
  • 數字:2
  • 日期:3
  • 布爾:4
  • error:5

9.讀取單元格中的日期

首先判斷ctype是否等于3,如果為3,則用時間格式處理。先使用xlrd.xldate_as_tuple()方法來處理,將date類型的數據轉換成元組。1991/11/11 -> (1991,11,11,0,0,0)。然后使用date的strftime()方法進行格式化。 (1991,11,11,0,0,0) -> 1991/11/11

if (sheet.cell(row,col).ctype == 3):date_value = xlrd.xldate_as_tuple(sheet.cell_value(rows,3),book.datemode)date_tmp = date(*date_value[:3]).strftime('%Y/%m/%d')

ndarray 與 list 互相轉換

參考博客

np.array(a) # list 轉 numpy a.tolist() # ndarray 轉 list

兩組點組算歐式距離

In [1]: from scipy.spatial.distance import cdist...: import numpy as np...: x1 =np.array([(1,3),(2,4),(5,6)])...: x2 =[(3,7),(4,8),(6,9)]...: cdist(x1,x2,metric='euclidean')...: Out[1]: array([[ 4.47213595, 5.83095189, 7.81024968],[ 3.16227766, 4.47213595, 6.40312424],[ 2.23606798, 2.23606798, 3.16227766]])

openpyxl操作excel文件

參考官方文檔

1.新建工作表

from openpyxl import Workbook wb = Workbook()

一個工作表至少有一個工作簿. 你可以通過 Workbook.active 來獲取這個屬性:

>>> ws = wb.active

給工作簿命名后,就可以將其作為工作簿的鍵:

ws3 = wb["New Title"]

2.新建工作簿

>>> ws1 = wb.create_sheet("Mysheet") # insert at the end (default) # or >>> ws2 = wb.create_sheet("Mysheet", 0) # insert at first position # or >>> ws3 = wb.create_sheet("Mysheet", -1) # insert at the penultimate position

3.修改工作簿名稱,工作簿選項卡背景色

ws.title = "New Title" ws.sheet_properties.tabColor = "1072BA"

4. 查看工作簿中所有工作表的名稱

>>> print(wb.sheetnames) ['Sheet2', 'New Title', 'Sheet1'] >>> for sheet in wb:print(sheet.title)

5.復制工作簿

一個工作表中創建一個工作簿的復制:

>>> source = wb.active >>> target = wb.copy_worksheet(source)

6.訪問單元格

>>> c = ws['A4'] >>> ws['A4'] = 4 >>> d = ws.cell(row=4, column=2, value=10)

當工作薄在內存中被創建之后并沒有單元格 cells ,單元格只有在被第一次訪問(access)的時候才會創建.由于這個特性,即使你未對單元格賦值,滾動瀏覽而非直接訪問時也會在內存中直接創建。

# 切片訪問單元格 >>> cell_range = ws['A1':'C2'] >>> colC = ws['C'] >>> col_range = ws['C:D'] >>> row10 = ws[10] >>> row_range = ws[5:10] # 遍歷訪問單元格 # Worksheet.iter_rows 方法: >>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2): ... for cell in row: ... print(cell) <Cell Sheet1.A1> <Cell Sheet1.B1> <Cell Sheet1.C1> <Cell Sheet1.A2> <Cell Sheet1.B2> <Cell Sheet1.C2> # Worksheet.iter_cols 方法 >>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2): ... for cell in col: ... print(cell) <Cell Sheet1.A1> <Cell Sheet1.A2> <Cell Sheet1.B1> <Cell Sheet1.B2> <Cell Sheet1.C1> <Cell Sheet1.C2> # Worksheet.rows 屬性 >>> ws = wb.active >>> ws['C9'] = 'hello world' >>> tuple(ws.rows) ((<Cell Sheet.A1>, <Cell Sheet.B1>, <Cell Sheet.C1>), (<Cell Sheet.A2>, <Cell Sheet.B2>, <Cell Sheet.C2>), (<Cell Sheet.A3>, <Cell Sheet.B3>, <Cell Sheet.C3>), (<Cell Sheet.A4>, <Cell Sheet.B4>, <Cell Sheet.C4>), (<Cell Sheet.A5>, <Cell Sheet.B5>, <Cell Sheet.C5>), (<Cell Sheet.A6>, <Cell Sheet.B6>, <Cell Sheet.C6>), (<Cell Sheet.A7>, <Cell Sheet.B7>, <Cell Sheet.C7>), (<Cell Sheet.A8>, <Cell Sheet.B8>, <Cell Sheet.C8>), (<Cell Sheet.A9>, <Cell Sheet.B9>, <Cell Sheet.C9>))# Worksheet.columns 屬性 >>> tuple(ws.columns) ((<Cell Sheet.A1>, <Cell Sheet.A2>, <Cell Sheet.A3>, <Cell Sheet.A4>, <Cell Sheet.A5>, <Cell Sheet.A6>, ... <Cell Sheet.B7>, <Cell Sheet.B8>, <Cell Sheet.B9>), (<Cell Sheet.C1>, <Cell Sheet.C2>, <Cell Sheet.C3>, <Cell Sheet.C4>, <Cell Sheet.C5>, <Cell Sheet.C6>, <Cell Sheet.C7>, <Cell Sheet.C8>, <Cell Sheet.C9>))

7.僅訪問單元格值

如果你只想要工作薄的值,你可以使用 Worksheet.values 屬性。

for row in ws.values:for value in row:print(value)

Worksheet.iter_rows 和 Worksheet.iter_cols 可以用 values_only 參數來返回單元格值:

>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True): ... print(row)(None, None, None) (None, None, None)

8.保存至文件

保存工作表最簡單和安全的方法就是使用 Workbook 類的 Workbook.save() 方法:

>>> wb = Workbook() >>> wb.save('balances.xlsx')

這個操作將會無警告直接覆蓋已有文件

如果想把文件保存成流。例如當使用 Pyramid, Flask 或 Django 等 web 應用程序時

>>> from tempfile import NamedTemporaryFile >>> from openpyxl import Workbook >>> wb = Workbook() >>> with NamedTemporaryFile() as tmp:wb.save(tmp.name)tmp.seek(0)stream = tmp.read()

9.從文件加載

可以使用 openpyxl.load_workbook() 方法來打開一個已存在的工作表:

>>> from openpyxl import load_workbook >>> wb2 = load_workbook('test.xlsx') >>> print wb2.sheetnames ['Sheet2', 'New Title', 'Sheet1']

10.寫入工作表

>>> from openpyxl import Workbook >>> from openpyxl.utils import get_column_letter >>> >>> wb = Workbook() >>> >>> dest_filename = 'empty_book.xlsx' >>> >>> ws1 = wb.active >>> ws1.title = "range names" >>> >>> for row in range(1, 40): ... ws1.append(range(600)) >>> >>> ws2 = wb.create_sheet(title="Pi") >>> >>> ws2['F5'] = 3.14 >>> >>> ws3 = wb.create_sheet(title="Data") >>> for row in range(10, 20): ... for col in range(27, 54): ... _ = ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col))) >>> print(ws3['AA10'].value) AA >>> wb.save(filename = dest_filename)

11.更改時間格式

>>> import datetime >>> from openpyxl import Workbook >>> wb = Workbook() >>> ws = wb.active >>> # set date using a Python datetime >>> ws['A1'] = datetime.datetime(2010, 7, 21) >>> >>> ws['A1'].number_format 'yyyy-mm-dd h:mm:ss'

12.合并/拆分單元格

會保留左上角的單元格值

>>> from openpyxl.workbook import Workbook >>> >>> wb = Workbook() >>> ws = wb.active >>> >>> ws.merge_cells('A2:D2') >>> ws.unmerge_cells('A2:D2') >>> >>> # or equivalently >>> ws.merge_cells(start_row=2, start_column=1, end_row=4, end_column=4) >>> ws.unmerge_cells(start_row=2, start_column=1, end_row=4, end_column=4)

13.插入圖像

>>> from openpyxl import Workbook >>> from openpyxl.drawing.image import Image >>> >>> wb = Workbook() >>> ws = wb.active >>> ws['A1'] = 'You should see three logos below' >>> # create an image >>> img = Image('logo.png') >>> # add to worksheet and anchor next to cells >>> ws.add_image(img, 'A1') >>> wb.save('logo.xlsx')

14.隱藏列號和行號

>>> import openpyxl >>> wb = openpyxl.Workbook() >>> ws = wb.create_sheet() >>> ws.column_dimensions.group('A','D', hidden=True) >>> ws.row_dimensions.group(1,10, hidden=True) >>> wb.save('group.xlsx')

15.插入/刪除行或列,移動范圍單元格

openpyxl.worksheet.worksheet.Worksheet.insert_rows() openpyxl.worksheet.worksheet.Worksheet.insert_cols() openpyxl.worksheet.worksheet.Worksheet.delete_rows() openpyxl.worksheet.worksheet.Worksheet.delete_cols() # 默認是一行或一列。 例如在第七行插入一行 (存在第七行): >>> ws.insert_rows(7) # 刪除 F:H 列: >>> ws.delete_cols(6, 3) # 在一個工作表內移動范圍單元格: >>> ws.move_range("D4:F10", rows=-1, cols=2) # 這會將 D4:F10 單元格向上移動一行向右移動兩列,已存在的單元格將會被覆蓋

16.將Pandas Dataframes寫入工作簿

from openpyxl.utils.dataframe import dataframe_to_rows wb = Workbook() ws = wb.activefor r in dataframe_to_rows(df, index=True, header=True):ws.append(r)

Python基礎語法

1.enumerate() 函數

>>> seq = ['one', 'two', 'three'] >>> for i, element in enumerate(seq): ... print i, element ... 0 one 1 two 2 three

2.List index()方法

list.index(x[, start[, end]])

  • x-- 查找的對象。
  • start-- 可選,查找的起始位置。
  • end-- 可選,查找的結束位置。
#!/usr/bin/python # -*- coding: UTF-8 -*-aList = [123, 'xyz', 'runoob', 'abc']print "xyz 索引位置: ", aList.index( 'xyz' ) print "runoob 索引位置 : ", aList.index( 'runoob', 1, 3 )

Python turtle庫

1.移動和繪制

turtle.forward(distance) # 海龜前進 distance 指定的距離,方向為海龜的朝向。 turtle.back(distance) # 海龜后退 distance 指定的距離,方向與海龜的朝向相反。不改變海龜的朝向。 turtle.right(angle) # 海龜右轉 angle 個單位。(單位默認為角度,但可通過 degrees() 和 radians() 函數改變設置。) 角度的正負由海龜模式確定 turtle.left(angle) # 海龜左轉 angle 個單位。 turtle.setpos(x, y=None) # 如果 y 為 None,x 應為一個表示坐標的數值對或 Vec2D 類對象 (例如 pos() 返回的對象).海龜移動到一個絕對坐標。如果畫筆已落下將會畫線。不改變海龜的朝向。 # 例如: tp = turtle.pos() turtle.setpos(60,30) turtle.setpos(tp) # turtle.setx(x) # 設置海龜的橫坐標為 x,縱坐標保持不變。 turtle.sety(y) # 設置海龜的縱坐標為 y,橫坐標保持不變。 turtle.setheading(to_angle) # 設置海龜的朝向為 to_angle。 # 標準模式 0 - 東 90 - 北 180 - 西 270 - 南 # logo 模式 0 - 北 90 - 東 180 - 南 270 - 西 turtle.home() # 海龜移至初始坐標 (0,0),并設置朝向為初始方向 turtle.circle(radius, extent=None, steps=None) # 繪制一個 radius 指定半徑的圓。圓心在海龜左邊 radius 個單位;extent 為一個夾角,用來決定繪制圓的一部分。如未指定 extent則繪制整個圓。如果 extent 不是完整圓周,則以當前畫筆位置為一個端點繪制圓弧。如果 radius 為正值則朝逆時針方向繪制圓弧,否則朝順時針方向。最終海龜的朝向會依據 extent 的值而改變。圓實際是以其內切正多邊形來近似表示的,其邊的數量由 steps 指定。如果未指定邊數則會自動確定。此方法也可用來繪制正多邊形。 turtle.dot(size=None, *color) # 繪制一個直徑為 size,顏色為 color 的圓點。如果 size 未指定,則直徑取 pensize+4 和 2*pensize 中的較大值。 turtle.undo() # 撤消 (或連續撤消) 最近的一個 (或多個) 海龜動作。可撤消的次數由撤消緩沖區的大小決定。 turtle.speed(speed=None) # 設置海龜移動的速度為 0..10 表示的整型數值。如未指定參數則返回當前速度。如果輸入數值大于 10 或小于 0.5 則速度設為 0。速度字符串與速度值的對應關系如下:"fastest": 0 最快 "fast": 10 快 "normal": 6 正常 "slow": 3 慢 "slowest": 1 最慢 # speed = 0 表示 沒有 動畫效果。forward/back 將使海龜向前/向后跳躍,同樣的 left/right 將使海龜立即改變朝向。

2.獲取海龜的狀態

turtle.position() # 返回海龜當前的坐標 (x,y) turtle.pos() turtle.towards(x, y=None) # 返回從海龜位置到由 (x,y)、矢量或另一海龜所確定位置的連線的夾角。 此數值依賴于海龜的初始朝向,這又取決于 "standard"/"world" 或 "logo" 模式設置。 # 例 turtle.goto(10, 10) turtle.towards(0,0) # turtle.xcor() # 返回海龜的 x 坐標。 turtle.ycor() # 返回海龜的 y 坐標。 turtle.heading() # 返回海龜當前的朝向 turtle.distance(x, y=None) # 返回從海龜位置到由 (x,y),適量或另一海龜對應位置的單位距離

3.度量單位設置

turtle.degrees(fullcircle=360.0) # 設置角度的度量單位,即設置一個圓周為多少 "度"。默認值為 360 度。 turtle.radians() # 設置角度的度量單位為弧度。其值等于 degrees(2*math.pi)。

4.畫筆控制——繪圖狀態

turtle.pendown() turtle.pd() turtle.down() # 畫筆落下 -- 移動時將畫線。 turtle.penup() turtle.pu() turtle.up() # 畫筆抬起 -- 移動時不畫線。 turtle.pensize(width=None) turtle.width(width=None) # 設置線條的粗細為 width 或返回該值。如未指定參數,則返回當前的 pensize。 # 例 >>> turtle.pensize() 1 >>> turtle.pensize(10) # turtle.pen(pen=None, **pendict) # 返回或設置畫筆的屬性,以一個包含以下鍵值對的 "畫筆字典" 表示: turtle.isdown() # 如果畫筆落下返回 True,如果畫筆抬起返回 False。

5.畫筆控制——顏色控制

turtle.pencolor(*args) # 返回或設置畫筆顏色。 turtle.fillcolor(*args) # 返回或設置填充顏色。 turtle.color(*args) # 返回以一對顏色描述字符串或元組表示的當前畫筆顏色和填充顏色,兩者可分別由 pencolor() 和 fillcolor() 返回。

6.畫筆控制——填充

turtle.filling() # 返回填充狀態 (填充為 True,否則為 False)。 turtle.begin_fill() # 在繪制要填充的形狀之前調用。 turtle.end_fill() # 填充上次調用 begin_fill() 之后繪制的形狀。>>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(80) >>> turtle.end_fill()

7.畫筆控制——更多繪圖控制

turtle.reset() # 從屏幕中刪除海龜的繪圖,海龜回到原點并設置所有變量為默認值。 turtle.clear() # 從屏幕中刪除指定海龜的繪圖。不移動海龜。海龜的狀態和位置以及其他海龜的繪圖不受影響。 turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal')) # 基于 align ("left", "center" 或 "right") 并使用給定的字體將文本 —— arg 的字符串表示形式 —— 寫到當前海龜位置。 如果 move 為真值,畫筆會移至文本的右下角。 默認情況下 move 為 False。

8.海龜狀態

turtle.hideturtle() turtle.ht() # 使海龜不可見。當你繪制復雜圖形時這是個好主意,因為隱藏海龜可顯著加快繪制速度。 turtle.showturtle() turtle.st() # 使海龜可見。 turtle.isvisible() # 如果海龜顯示返回 True,如果海龜隱藏返回 False。

Python plotly_express庫

1.散點圖

# x and y given as array_like objects import plotly.express as px fig = px.scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16]) fig.show()

# x and y given as DataFrame columns import plotly.express as px df = px.data.iris() # iris is a pandas DataFrame fig = px.scatter(df, x="sepal_width", y="sepal_length") fig.show()

import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",size='petal_length', hover_data=['petal_width']) fig.show()

import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", color='petal_length') fig.show()

import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", symbol="species") fig.show()

import plotly.express as px df = px.data.iris() df["e"] = df["sepal_width"]/100 fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",error_x="e", error_y="e") fig.show()

import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_length", y="sepal_width", marginal_x="histogram", marginal_y="rug") fig.show()

import plotly.express as px df = px.data.tips() fig = px.scatter(df, x="total_bill", y="tip", color="smoker", facet_col="sex", facet_row="time") fig.show()

import plotly.express as pxdf = px.data.tips() fig = px.scatter(df, x="total_bill", y="tip", trendline="ols") fig.show()

2.折線圖

import plotly.express as px import numpy as npt = np.linspace(0, 2*np.pi, 100)fig = px.line(x=t, y=np.cos(t), labels={'x':'t', 'y':'cos(t)'}) fig.show()

import plotly.express as px df = px.data.gapminder().query("continent == 'Oceania'") fig = px.line(df, x='year', y='lifeExp', color='country') fig.show()

import plotly.express as px df = px.data.gapminder().query("continent == 'Oceania'") fig = px.line(df, x='year', y='lifeExp', color='country', markers=True) fig.show()

import plotly.express as px df = px.data.gapminder().query("continent == 'Oceania'") fig = px.line(df, x='year', y='lifeExp', color='country', symbol="country") fig.show()

import plotly.express as pxdf = px.data.stocks() fig = px.line(df, x='date', y="GOOG") fig.show()

import plotly.express as px import pandas as pddf = pd.DataFrame(dict(x = [1, 3, 2, 4],y = [1, 2, 3, 4] )) fig = px.line(df, x="x", y="y", title="Unsorted Input") fig.show()df = df.sort_values(by="x") fig = px.line(df, x="x", y="y", title="Sorted Input") fig.show()


import plotly.express as pxdf = px.data.gapminder().query("country in ['Canada', 'Botswana']")fig = px.line(df, x="lifeExp", y="gdpPercap", color="country", text="year") fig.update_traces(textposition="bottom right") fig.show()

3.import plotly.graph_objects as go

import plotly.graph_objects as go import numpy as npN = 1000 t = np.linspace(0, 10, 100) y = np.sin(t)fig = go.Figure(data=go.Scatter(x=t, y=y, mode='markers'))fig.show()

import plotly.graph_objects as go# Create random data with numpy import numpy as np np.random.seed(1)N = 100 random_x = np.linspace(0, 1, N) random_y0 = np.random.randn(N) + 5 random_y1 = np.random.randn(N) random_y2 = np.random.randn(N) - 5fig = go.Figure()# Add traces fig.add_trace(go.Scatter(x=random_x, y=random_y0,mode='markers',name='markers')) fig.add_trace(go.Scatter(x=random_x, y=random_y1,mode='lines+markers',name='lines+markers')) fig.add_trace(go.Scatter(x=random_x, y=random_y2,mode='lines',name='lines'))fig.show()

import plotly.graph_objects as gofig = go.Figure(data=go.Scatter(x=[1, 2, 3, 4],y=[10, 11, 12, 13],mode='markers',marker=dict(size=[40, 60, 80, 100],color=[0, 1, 2, 3]) ))fig.show()

import plotly.graph_objects as go import pandas as pddata= pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv")fig = go.Figure(data=go.Scatter(x=data['Postal'],y=data['Population'],mode='markers',marker_color=data['Population'],text=data['State'])) # hover text goes herefig.update_layout(title='Population of USA States') fig.show()

import plotly.graph_objects as gox = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]fig = go.Figure()fig.add_trace(go.Scatter(x=x,y=[10, 20, None, 15, 10, 5, 15, None, 20, 10, 10, 15, 25, 20, 10],name = '<b>No</b> Gaps', # Style name/legend entry with html tagsconnectgaps=True # override default to connect the gaps )) fig.add_trace(go.Scatter(x=x,y=[5, 15, None, 10, 5, 0, 10, None, 15, 5, 5, 10, 20, 15, 5],name='Gaps', ))fig.show()

import plotly.graph_objects as go import numpy as npx = np.array([1, 2, 3, 4, 5]) y = np.array([1, 3, 2, 3, 1])fig = go.Figure() fig.add_trace(go.Scatter(x=x, y=y, name="linear",line_shape='linear')) fig.add_trace(go.Scatter(x=x, y=y + 5, name="spline",text=["tweak line smoothness<br>with 'smoothing' in line object"],hoverinfo='text+name',line_shape='spline')) fig.add_trace(go.Scatter(x=x, y=y + 10, name="vhv",line_shape='vhv')) fig.add_trace(go.Scatter(x=x, y=y + 15, name="hvh",line_shape='hvh')) fig.add_trace(go.Scatter(x=x, y=y + 20, name="vh",line_shape='vh')) fig.add_trace(go.Scatter(x=x, y=y + 25, name="hv",line_shape='hv'))fig.update_traces(hoverinfo='text+name', mode='lines+markers') fig.update_layout(legend=dict(y=0.5, traceorder='reversed', font_size=16))fig.show()

import plotly.graph_objects as go import numpy as nptitle = 'Main Source for News' labels = ['Television', 'Newspaper', 'Internet', 'Radio'] colors = ['rgb(67,67,67)', 'rgb(115,115,115)', 'rgb(49,130,189)', 'rgb(189,189,189)']mode_size = [8, 8, 12, 8] line_size = [2, 2, 4, 2]x_data = np.vstack((np.arange(2001, 2014),)*4)y_data = np.array([[74, 82, 80, 74, 73, 72, 74, 70, 70, 66, 66, 69],[45, 42, 50, 46, 36, 36, 34, 35, 32, 31, 31, 28],[13, 14, 20, 24, 20, 24, 24, 40, 35, 41, 43, 50],[18, 21, 18, 21, 16, 14, 13, 18, 17, 16, 19, 23], ])fig = go.Figure()for i in range(0, 4):fig.add_trace(go.Scatter(x=x_data[i], y=y_data[i], mode='lines',name=labels[i],line=dict(color=colors[i], width=line_size[i]),connectgaps=True,))# endpointsfig.add_trace(go.Scatter(x=[x_data[i][0], x_data[i][-1]],y=[y_data[i][0], y_data[i][-1]],mode='markers',marker=dict(color=colors[i], size=mode_size[i])))fig.update_layout(xaxis=dict(showline=True,showgrid=False,showticklabels=True,linecolor='rgb(204, 204, 204)',linewidth=2,ticks='outside',tickfont=dict(family='Arial',size=12,color='rgb(82, 82, 82)',),),yaxis=dict(showgrid=False,zeroline=False,showline=False,showticklabels=False,),autosize=False,margin=dict(autoexpand=False,l=100,r=20,t=110,),showlegend=False,plot_bgcolor='white' )annotations = []# Adding labels for y_trace, label, color in zip(y_data, labels, colors):# labeling the left_side of the plotannotations.append(dict(xref='paper', x=0.05, y=y_trace[0],xanchor='right', yanchor='middle',text=label + ' {}%'.format(y_trace[0]),font=dict(family='Arial',size=16),showarrow=False))# labeling the right_side of the plotannotations.append(dict(xref='paper', x=0.95, y=y_trace[11],xanchor='left', yanchor='middle',text='{}%'.format(y_trace[11]),font=dict(family='Arial',size=16),showarrow=False)) # Title annotations.append(dict(xref='paper', yref='paper', x=0.0, y=1.05,xanchor='left', yanchor='bottom',text='Main Source for News',font=dict(family='Arial',size=30,color='rgb(37,37,37)'),showarrow=False)) # Source annotations.append(dict(xref='paper', yref='paper', x=0.5, y=-0.1,xanchor='center', yanchor='top',text='Source: PewResearch Center & ' +'Storytelling with data',font=dict(family='Arial',size=12,color='rgb(150,150,150)'),showarrow=False))fig.update_layout(annotations=annotations)fig.show()

import plotly.graph_objects as go import numpy as npx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x_rev = x[::-1]# Line 1 y1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y1_upper = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] y1_lower = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y1_lower = y1_lower[::-1]# Line 2 y2 = [5, 2.5, 5, 7.5, 5, 2.5, 7.5, 4.5, 5.5, 5] y2_upper = [5.5, 3, 5.5, 8, 6, 3, 8, 5, 6, 5.5] y2_lower = [4.5, 2, 4.4, 7, 4, 2, 7, 4, 5, 4.75] y2_lower = y2_lower[::-1]# Line 3 y3 = [10, 8, 6, 4, 2, 0, 2, 4, 2, 0] y3_upper = [11, 9, 7, 5, 3, 1, 3, 5, 3, 1] y3_lower = [9, 7, 5, 3, 1, -.5, 1, 3, 1, -1] y3_lower = y3_lower[::-1]fig = go.Figure()fig.add_trace(go.Scatter(x=x+x_rev,y=y1_upper+y1_lower,fill='toself',fillcolor='rgba(0,100,80,0.2)',line_color='rgba(255,255,255,0)',showlegend=False,name='Fair', )) fig.add_trace(go.Scatter(x=x+x_rev,y=y2_upper+y2_lower,fill='toself',fillcolor='rgba(0,176,246,0.2)',line_color='rgba(255,255,255,0)',name='Premium',showlegend=False, )) fig.add_trace(go.Scatter(x=x+x_rev,y=y3_upper+y3_lower,fill='toself',fillcolor='rgba(231,107,243,0.2)',line_color='rgba(255,255,255,0)',showlegend=False,name='Ideal', )) fig.add_trace(go.Scatter(x=x, y=y1,line_color='rgb(0,100,80)',name='Fair', )) fig.add_trace(go.Scatter(x=x, y=y2,line_color='rgb(0,176,246)',name='Premium', )) fig.add_trace(go.Scatter(x=x, y=y3,line_color='rgb(231,107,243)',name='Ideal', ))fig.update_traces(mode='lines') fig.show()

總結

以上是生活随笔為你收集整理的144个城市坐标Python程序的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。