Pandas Dataframe 선 그래프가 x축에 날짜를 표시합니다
문제:
플롯을 시도할 때 x축에 날짜가 있는 Pandas DataFrame을 사용하면 matplotlib 라이브러리가 부정확한 형식을 생성하고 데이터와 정확하게 일치하지 않는 날짜를 생성합니다.
답변:
비호환성 Pandas와 Matplotlib의 datetime 유틸리티 사이의 문제가 이 문제의 근본 원인입니다. Pandas는 날짜/시간 객체에 대해 비표준 부동 소수점 표현을 사용합니다. 이는 Matplotlib의 자체 날짜 형식 지정 방법과 호환되지 않습니다.
해결책:
이 문제를 해결하려면 다음이 필요합니다. 두 가지 가능한 접근 방식이 있습니다.
-
Pandas 날짜 형식을 비활성화합니다.
DataFrame을 그릴 때 x_compat=True를 설정하면 Pandas는 Matplotlib의 내부 날짜를 사용합니다. 서식 메커니즘을 사용하면 x축 서식을 보다 정확하게 제어할 수 있습니다.
-
Matplotlib를 플로팅 및 서식 지정에만 사용하세요.
날짜 플로팅을 위해 Pandas에서는 Matplotlib의 자체 메서드를 사용하여 날짜 값과 형식을 처리할 수 있습니다. 이를 통해 유연성이 향상되고 필요에 따라 날짜 형식을 사용자 정의할 수 있습니다.
다음은 두 가지 접근 방식을 모두 보여주는 업데이트된 예입니다.
<code class="python">import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as dates df = pd.DataFrame({'date': ['20170527', '20170526', '20170525'], 'ratio1': [1, 0.98, 0.97]}) df['date'] = pd.to_datetime(df['date']) usePandas = True # Either use Pandas if usePandas: df = df.set_index('date') ax = df.plot(x_compat=True, figsize=(6, 4)) ax.xaxis.set_major_locator(dates.DayLocator()) ax.xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a')) ax.invert_xaxis() ax.get_figure().autofmt_xdate(rotation=0, ha="center") # or use Matplotlib else: fig, ax = plt.subplots(figsize=(6, 4)) ax.plot('date', 'ratio1', data=df) ax.xaxis.set_major_locator(dates.DayLocator()) ax.xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a')) fig.invert_xaxis() plt.show()</code>
이 중 하나를 사용합니다. 접근 방식을 사용하면 정확한 형식을 사용하여 Pandas DataFrame 플롯의 x축에 날짜/시간 값을 효과적으로 표시할 수 있습니다.
위 내용은 Pandas DataFrame 선 플롯의 X축에 날짜를 올바르게 표시하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

Dreamweaver Mac版
시각적 웹 개발 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!