python matplotlib 画两条折线图 其中一组数据有空值 如何处理？

python matplotlib 画两条折线图 其中一组数据有空值 如何处理？

import csv
from datetime import datetime
from matplotlib import pyplot as plt

filename = 'data.csv'
with open(filename) as f:

dates = []
temp1 = []
temp2 = []

time = row[1] + '-' + row[2] + '-' + row[3]
current_date = datetime.strptime(time, "%Y-%m-%d")
dates.append(current_date)

tempm1 = int(float(row[7]))
temp1.append(tempm1)

tempm2 = int(row[28])
temp2.append(tempm2)


fig = plt.figure(dpi=128, figsize=(10,6))
plt.plot(dates, temp1, c='red')
plt.plot(dates, temp2, c='blue')

plt.show()

C:\Users\yo\AppData\Local\Programs\Python\Python37\python.exe F:/论文/data/compare/compare.py
Traceback (most recent call last):
File "F:/论文/data/compare/compare.py", line 26, in
tempm2 = int(row[28])
ValueError: invalid literal for int() with base 10: '20.075'

Process finished with exit code 1

1个回答

python matplotlib.pyplot画折线图

python使用matplotlib.pyplot绘制折线图纵坐标（y轴）与实际图内坐标不符，请问是什么原因呢？

python使用matplotlib.pyplot绘制折线图纵坐标（y轴）与实际图内坐标不符，效果图如下 （右下角是实际坐标） ![图片说明](https://img-ask.csdn.net/upload/202005/30/1590812415_307302.png) 绘图代码如下  plt.subplot(121),plt.plot([160,1600,3200,6400,9600,12800,16000],[85.66261,75.2519,72.2787,69.2498,67.4960,66.2274,65.2696],'r-*') plt.subplot(122),plt.plot([160,1600,3200,6400,9600,12800,16000],[0.99999980,0.99999443,0.99998277,0.99994450,0.99990344,0.99986035,0.99981919]) plt.show() 

pandas绘制折线图问题

python Matplotlib 怎么把两个箱图分开，但要求在同一图上

python 为什么画出来的折线图是这个样子?

![图片说明](https://img-ask.csdn.net/upload/202005/21/1590048951_628186.png) #训练和验证的准确率，并作图显示 if(validation_size): validation_accuracy = accuracy.eval(session = sess,feed_dict={x:valiation_images, y_: validation_labels, keep_prob: 1.0}) print('validation_accuracy => %.4f'%(validation_accuracy)) plt.plot(x_range, train_accuracies,'-b', label='Training') plt.plot(x_range, validation_accuracies,'-g', label='Validation') plt.legend() plt.ylabel('accuracy') plt.xlabel('step') plt.xlim(0,1900) plt.ylim(0,1.1) plt.show()  >  

python matplotlib显示单色图问题

 def initArray(num): img = np.zeros((256,256)) for x in range(0,256): for y in range(0,256): img[x][y] = num return img fig = plt.figure() ax = fig.add_subplot() ax.imshow(initArray(20),cmap='gray') plt.show()  按说initArray的参数变化，显示的图片应该是不同的单色图，可是显示显示的全是黑色怎么回事？

python用matplotlib画K线

import matplotlib.pyplot as plt import matplotlib.finance as mpf with open('SH#600004.txt') as obj: text=obj.readlines() baseinfo=text[0] dayinfo=text[2:-1] date_list =[dayinfo[i].split(',')[0] for i in range(len(dayinfo))] open_list =[dayinfo[i].split(',')[1] for i in range(len(dayinfo))] high_list =[dayinfo[i].split(',')[2] for i in range(len(dayinfo))] low_list =[dayinfo[i].split(',')[3] for i in range(len(dayinfo))] close_list=[dayinfo[i].split(',')[4] for i in range(len(dayinfo))] quotes=zip(date_list,open_list,high_list,low_list,close_list) #N=100 #open_list[:N],high_list[:N],low_list[:N],close_list[:N] fig,ax=plt.subplots() mpf.candlestick_ohlc(ax,quotes,width=0.6,colorup='r',colordown='green') plt.title(baseinfo) plt.xlabel(date_list) plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 plt.show() **#以下是报错信息 C:\ProgramData\Anaconda3\python.exe G:/python/test/test.py C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py:106: MatplotlibDeprecationWarning: The finance module has been deprecated in mpl 2.0 and will be removed in mpl 2.2. Please use the module mpl_finance instead. warnings.warn(message, mplDeprecation, stacklevel=1) Traceback (most recent call last): File "G:/python/test/test.py", line 18, in <module> mpf.candlestick_ohlc(ax,quotes,width=0.6,colorup='r',colordown='green') File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\finance.py", line 737, in candlestick_ohlc alpha=alpha, ochl=False) File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\finance.py", line 794, in _candlestick height = open - close TypeError: unsupported operand type(s) for -: 'str' and 'str'** 我搜了下知道日期格式转换需要用到date2num这个函数 我的文本里面日期格式是XXXX/XX/XX的形式 请问quotes一项里日期需求的格式是什么?

matplotlib绘制k线图如何跳过周末等数据空白日期，让图形连贯起来？

#!/usr/bin/python # -*- coding: UTF-8 -*- from pylab import * import talib from pylab import * import mpl_finance as mpf from matplotlib.pylab import date2num import pandas as pd import datetime mpl.rcParams['font.sans-serif'] = ['SimHei'] quotes = [] stock = pd.read_csv('99999.csv', index_col=None) for row in range(260): sdate_plt = row print(sdate_plt) sopen = stock.loc[row, 'open'] shigh = stock.loc[row, 'high'] slow = stock.loc[row, 'low'] sclose = stock.loc[row, 'close'] datas = (sdate_plt, sopen, shigh, slow, sclose) # 按照 candlestick_ohlc 要求的数据结构准备数据 quotes.append(datas) fig, ax = plt.subplots(facecolor=(0, 0.3, 0.5), figsize=(12, 8)) fig.subplots_adjust(bottom=0.1) ax.xaxis_date() plt.xticks(rotation=45) # 日期显示的旋转角度 plt.title('2018年7月1日至今k线图',fontsize=18) plt.ylabel('价格（元）',fontsize=15) mpf.candlestick_ohlc(ax, quotes, width=0.7, colorup='r', colordown='green') # 上涨为红色K线，下跌为绿色，K线宽度为0.7 plt.annotate(s='brown x = buying; green x = selling',xy=('2016-7-11',4400), xytext=('2016-7-11',4400),bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k', lw=2, alpha=0.5)) plt.grid(axis='y',linestyle='-.') plt.show() 1.  ![图片说明](https://img-ask.csdn.net/upload/201908/22/1566463928_276488.png)

matplotlib如何做分组条形图？？

Python使用matplotlib绘图怎么把图的标题放到图下方

 plt.title('助攻表现（常规赛）') plt.ylabel('场均助攻数') plt.xlabel('年份-冠军球队') plt.ylim(17) plt.setp(plt.xticks(idx,tick)[1],rotation=90) plt.legend(bbox_to_anchor=(1.15,1)) plt.show()  怎么修改呢，像R那样把标题放在图下面

Python/matplotlib：已知空间上一点坐标和长宽高值，如何画出立方体？

matplotlib所绘制的图像在全屏查看时比例失调，怎么解决？

from scipy.stats.kde import gaussian_kde import numpy from scipy.io import netcdf import gdal from gdalconst import * #import numpy,osr,sys import netCDF4 import pdb import datetime from scipy import interpolate import scipy.io as sio import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap ,shiftgrid import numpy as np import math #import seawater as sw from scipy import interpolate from math import radians, cos, sin, asin, sqrt import netCDF4 import glob import os import datetime from matplotlib.path import Path from collections import Counter data=netCDF4.Dataset(os.path.join('E:\\HYcom1\\uv\\uv1\\hycom_glb_911_2016010100_t000_uv3z.nc')) latitudes = data.variables['lat'][1188:1626] longitudes = data.variables['lon'][750:2063] lons, lats = np.meshgrid(longitudes,latitudes) v=np.zeros([438,1313])#空的二维数组 u=np.zeros([438,1313])#空的二维数组 gird= [[0 for col in range(1313)] for row in range(438)] k=0 tempv=data.variables['water_v'][0][k] tempu=data.variables['water_u'][0][k] #k=4 for i in range(1188,1626): for j in range(750,2063): if math.isnan(tempv[i][j]): v[i-1188][j-750]=0 else: v[i-1188][j-750]=tempv[i][j] if math.isnan(tempu[i][j]): u[i-1188][j-750]=0 else: u[i-1188][j-750]=tempu[i][j] #将为nan的数值赋值为0 for i in range(0,438):#当分辨率改变时需要改变 for j in range(0,1313): gird[i][j]=math.sqrt(u[i][j]*u[i][j]+v[i][j]*v[i][j]) #格网数据标量化 for i in range (1,438,2): for j in range (1,1313,2): gird[i-1][j-1]=(gird[i-1][j-1]+gird[i-1][j]+gird[i][j-1]+gird[i][j])/4 for i in range (0,438): for j in range (0,1313): gird[i][j]=gird[int(i/2)*2][int(j/2)*2] #双for循环，第一个将范围内的平均值存在左上角的位置，第二个将左上角的数据赋值所选范围内 gird= np.array(gird) m = Basemap(llcrnrlon=60,urcrnrlon=165,llcrnrlat=15,urcrnrlat=50) fig = plt.figure(edgecolor='none',frameon='false')#1124 figsize=(8,4),dpi=20 fig.set_size_inches(64,21.4) x, y = m(lons, lats) m.bluemarble() m.pcolor(x,y,gird,cmap=plt.cm.RdBu_r) m.fillcontinents(color='#CCCCCC',lake_color='#CCCCCC')#,alpha=0.0 plt.subplots_adjust(top=1,bottom=0,left=0,right=1,hspace=0,wspace=0)#输出图像边框设置 plt.savefig(os.path.join(r'E:\34\prectice\1202\\'+'64214.png')) plt.close() 以上是代码，其中读取NC数据，将特定区域的信息进行提取，进行绘图，但是最终需要的是陆地透明化的![图片说明](https://img-ask.csdn.net/upload/201712/02/1512183403_250442.png) 而我出图只能出成这样的![图片说明](https://img-ask.csdn.net/upload/201712/02/1512183388_746963.png) 不知在Python中是否有操作可以是陆地透明化，亦或者陆地填充成NASA的地图图片也可以，但是海洋地区一定是要根据处理出来的值来画的！求解~~~

vs中使用python操作matplotlib时发生错误

C++(数据结构与算法)78:---分而治之

springboot+jwt实现token登陆权限认证

win10暴力查看wifi密码

MySQL数据库面试题（2020最新版）

!大部分程序员只会写3年代码

2020阿里全球数学大赛：3万名高手、4道题、2天2夜未交卷

HashMap底层实现原理，红黑树，B+树，B树的结构原理 Spring的AOP和IOC是什么？它们常见的使用场景有哪些？Spring事务，事务的属性，传播行为，数据库隔离级别 Spring和SpringMVC，MyBatis以及SpringBoot的注解分别有哪些？SpringMVC的工作原理，SpringBoot框架的优点，MyBatis框架的优点 SpringCould组件有哪些，他们...

Python爬虫，高清美图我全都要（彼岸桌面壁纸）

Java岗开发3年，公司临时抽查算法，离职后这几题我记一辈子