Pandas Dataframe 선 도표에서 x축에 날짜 표시
소개
Pandas 선 도표의 x축에 날짜를 표시하려면 set_index () 메서드를 사용하면 날짜 값이 포함된 열을 DataFrame의 인덱스로 변환할 수 있습니다. 그러나 matplotlib의 DateFormatter 함수를 사용하여 날짜 형식을 지정할 때 특정 문제가 발생할 수 있습니다.
DateFormatter 문제
아래 이미지는 코드에 DateFormatter를 추가할 때 발생하는 문제를 보여줍니다.
[날짜 형식이 잘못된 선 그래프 이미지]
날짜가 5-25 대신 5-24에 시작하고 목요일이 2017년 5-25로 잘못 표시되었습니다. 이는 종종 시간대 때문입니다. pandas와 matplotlib datetime 유틸리티 간의 관련 문제 또는 비호환성.
Pandas와 Matplotlib Datetime 개체의 비호환성
Pandas와 matplotlib datetime 개체는 일반적으로 호환되지 않습니다. pandas로 생성된 날짜 축에서 matplotlib 날짜 객체를 사용하려고 하면 문제가 발생할 수 있습니다.
이에 대한 한 가지 이유는 pandas datetime 객체가 0001-01 이후의 시간(일)을 나타내는 부동 소수점 숫자로 변환되기 때문입니다. -01 UTC, 더하기 1. 이 형식은 matplotlib의 날짜/시간 형식과 다릅니다.
솔루션
x_compat 사용
날짜 형식 문제를 해결하려면 x_compat=True 인수를 사용할 수 있습니다. 플롯() 메소드에 전달됩니다. 이는 팬더에게 자체 날짜/시간 형식을 사용하지 않도록 지시하여 matplotlib의 티커, 위치 지정자 및 포맷터를 사용할 수 있도록 합니다.
Matplotlib로 날짜 시간 그리기
또는 더 정확한 날짜 시간 형식이 필요한 경우 matplotlib 플로팅과 서식 모두에 사용할 수 있습니다. 다음 코드 조각은 이 접근 방식을 보여줍니다.
<code class="python">import matplotlib.pyplot as plt import matplotlib.dates as dates # Create the DataFrame df = pd.DataFrame({'date':['20170527','20170526','20170525'],'ratio1':[1,0.98,0.97]}) df['date'] = pd.to_datetime(df['date']) # Create the line plot plt.plot(df['date'], df['ratio1']) # Set major locator and formatter for the x-axis plt.gca().xaxis.set_major_locator(dates.DayLocator()) plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a')) # Invert the x-axis for chronological order plt.gca().invert_xaxis() # Autofmt the x-axis for optimal placement of dates plt.gcf().autofmt_xdate(rotation=0, ha="center") # Display the plot plt.show()</code>
이 수정된 코드는 x축에 정확한 형식의 날짜가 포함된 선 그래프를 생성합니다.
위 내용은 Pandas Line Plot의 x축에 날짜를 올바르게 표시하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

forhandlinglargedatasetsinpython, usenumpyarraysforbetterperformance.1) numpyarraysarememory-effic andfasterfornumericaloperations.2) leveragevectorization foredtimecomplexity.4) managemoryusage withorfications data

inpython, listsusedyammoryAllocation과 함께 할당하고, whilempyarraysallocatefixedMemory.1) listsAllocatemememorythanneedInitiality.

Inpython, youcansspecthedatatypeyfelemeremodelerernspant.1) usenpynernrump.1) usenpynerp.dloatp.ploatm64, 포모 선례 전분자.

numpyissentialfornumericalcomputinginpythonduetoitsspeed, memory-efficiency 및 comperniveMathematicaticaltions

contiguousUousUousUlorAllocationScrucialForraysbecauseItAllowsOfficationAndFastElementAccess.1) ItenableSconstantTimeAccess, o (1), DuetodirectAddressCalculation.2) Itimprovesceeffiency theMultipleementFetchespercacheline.3) Itsimplififiesmomorym

slicepaythonlistisdoneusingthesyntaxlist [start : step : step] .here'showitworks : 1) startistheindexofthefirstelementtoinclude.2) stopistheindexofthefirstelemement.3) stepisincrementbetwetweentractionsoftortionsoflists

NumpyAllowsForVariousOperationsOnArrays : 1) BasicArithmeticLikeadDition, Subtraction, A 및 Division; 2) AdvancedOperationsSuchasmatrixmultiplication; 3) extrayintondsfordatamanipulation; 5) Ag

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

드림위버 CS6
시각적 웹 개발 도구
