logo
down
shadow

Color mapping of data on a date vs time plot


Color mapping of data on a date vs time plot

Content Index :

Color mapping of data on a date vs time plot
Tag : python , By : Noah
Date : November 29 2020, 04:01 AM

I hope this helps . imshow requires a 2d array as input. You'll need to reformat your data into a 2d array: Date x Time with Tgrad as your values. Pandas makes this fairly easy with pivot. It does require that you have nicely spaced data points, i.e., a grid-like data set (same Time values for each Date). The post you linked would be useful if data points were not neatly scattered in 2d space. Also, there's no need to convert to a numpy array as matplotlib can handle dataframes.
C = data.pivot(index='Time', columns='Date', values='Tgrad')

fig, ax = plt.subplots()
ax.imshow(C)

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Plot elapsed time on x axis using date indexed time-series data


Tag : python , By : Mostapen
Date : March 29 2020, 07:55 AM
should help you out In my pandas dataframe, my time series data is indexed by absolute time (a date of format YYYY-MM-DD HH24:MI:SS.nnnnn): , You can convert your datetimeindex to a timedeltaindex and then plot.
df.index = df.index - df.index[0]
df.plot()

How to plot multi-color line if x-axis is date time index of pandas


Tag : python , By : Steve O.
Date : March 29 2020, 07:55 AM
it fixes the issue To produce a multi-colored line, you will need to convert the dates to numbers first, as matplotlib internally only works with numeric values.
For the conversion matplotlib provides matplotlib.dates.date2num. This understands datetime objects, so you would first need to convert your time series to datetime using series.index.to_pydatetime() and then apply date2num.
s = pd.Series(y, index=dates)
inxval = mdates.date2num(s.index.to_pydatetime())
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
from matplotlib.collections import LineCollection

dates = pd.date_range("2017-01-01", "2017-06-20", freq="7D" )
y = np.cumsum(np.random.normal(size=len(dates)))

s = pd.Series(y, index=dates)

fig, ax = plt.subplots()

#convert dates to numbers first
inxval = mdates.date2num(s.index.to_pydatetime())
points = np.array([inxval, s.values]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)

lc = LineCollection(segments, cmap="plasma", linewidth=3)
# set color to date values
lc.set_array(inxval)
# note that you could also set the colors according to y values
# lc.set_array(s.values)
# add collection to axes
ax.add_collection(lc)


ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator())
monthFmt = mdates.DateFormatter("%b")
ax.xaxis.set_major_formatter(monthFmt)
ax.autoscale_view()
plt.show()
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np; np.random.seed(42)
from matplotlib.collections import LineCollection

dates = np.arange("2017-01-01", "2017-06-20", dtype="datetime64[D]" )
y = np.cumsum(np.random.normal(size=len(dates)))
c = np.cumsum(np.random.normal(size=len(dates)))


fig, ax = plt.subplots()

#convert dates to numbers first
inxval = mdates.date2num(dates)
points = np.array([inxval, y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)

lc = LineCollection(segments, cmap="plasma", linewidth=3)
# set color to date values
lc.set_array(c)
ax.add_collection(lc)

ax.xaxis_date()
ax.autoscale_view()
plt.show()

How to plot LTP vs. time from data available in a matrix in the form of Date, time, LTP


Tag : r , By : mikhaelrasputin
Date : March 29 2020, 07:55 AM
This might help you I have data in 3 columns:(as shown below , Try this:
library(zoo)
z <- read.zoo("myfile.dat", header = TRUE, index = 1:2, format = "%Y%m%d %H:%M", tz = "")

# classic graphics
plot(z)

# ggplot2 graphics
autoplot(z)
cat("Date Time LTP\n20180102 09:16 1800", file = "myfile.dat")

How to plot date-time and value_counts() of non numerical data?


Tag : python , By : nhuser
Date : March 29 2020, 07:55 AM
like below fixes the issue You're really close!
Once your connect_start column has been transformed to datetime, you can extract month or day like this:
df["my_date_column"].dt.day
# import modules
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(2019)

##############################################
# Just for example: create a random dataset  #
##############################################

number_row = 10


def random_dates(start, end, n):
    """  Generate n random dates between the interval """
    start_u = pd.to_datetime(start).value//10**9
    end_u = pd.to_datetime(end).value//10**9
    return pd.to_datetime(np.random.randint(start_u, end_u, n), unit='s')

# create the dataframe
df = pd.DataFrame({"connect_start": random_dates("2019-01-01", "2019-12-31", number_row),
                   "advertisement_id": np.random.randint(0, 10, number_row)})

print(df)
#         connect_start  advertisement_id
# 0 2019-09-08 18: 34: 48                 0
# 1 2019-11-05 06: 30: 10                 0
# 2 2019-05-03 01: 32: 15                 7
# 3 2019-01-13 06: 37: 25                 8
# 4 2019-12-04 03: 47: 36                 5
# 5 2019-11-23 14: 12: 14                 3
# 6 2019-09-09 18: 39: 50                 0
# 7 2019-10-01 08: 38: 53                 2
# 8 2019-04-05 21: 37: 19                 5
# 9 2019-04-25 04: 26: 52                 7

##############################################
#                   Process                  #
##############################################

# Convert connect_start as datetime type
df["connect_start"] = pd.to_datetime(df.connect_start, format="%Y-%m-%d %H:%M:%S")

# Extract day of month, date, month in 3 new columns
df["day_in_month"] = df["connect_start"].dt.day
df["day_per_year"] = df['connect_start'].dt.date
df["month"] = df["connect_start"].dt.month

print(df)
#           connect_start  advertisement_id  day_in_month day_per_year  month
# 0 2019-09-08 18: 34: 48                 0             8   2019-09-08      9
# 1 2019-11-05 06: 30: 10                 0             5   2019-11-05     11
# 2 2019-05-03 01: 32: 15                 7             3   2019-05-03      5
# 3 2019-01-13 06: 37: 25                 8            13   2019-01-13      1
# 4 2019-12-04 03: 47: 36                 5             4   2019-12-04     12
# 5 2019-11-23 14: 12: 14                 3            23   2019-11-23     11
# 6 2019-09-09 18: 39: 50                 0             9   2019-09-09      9
# 7 2019-10-01 08: 38: 53                 2             1   2019-10-01     10
# 8 2019-04-05 21: 37: 19                 5             5   2019-04-05      4
# 9 2019-04-25 04: 26: 52                 7            25   2019-04-25      4


# Compute the number advertisement_id per group
df_day_in_month = df[["advertisement_id", "day_in_month"]].groupby(by="day_in_month").sum()
df_day_per_year = df[["advertisement_id", "day_per_year"]].groupby(by="day_per_year").sum()
df_month = df[["advertisement_id", "month"]].groupby(by="month").sum()

# Fulfill with 0 for all days off the month
df_day_in_month_all_days = df_day_in_month.reindex(np.arange(1, 32), fill_value=0)


#####################################
#               Diplay              #
#####################################
# Create figure
fig, axes = plt.subplots(nrows=2, ncols=2)

# Define subplots
df_day_in_month.plot.bar(ax=axes[0, 0], rot=0)
df_day_per_year.plot.bar(ax=axes[0, 1], rot=45)
df_day_in_month_all_days.plot.bar(ax=axes[1, 0], rot=0)
df_month.plot.bar(ax=axes[1, 1], rot=0)

# Prevent plot overlapping
plt.tight_layout()
plt.show()

How to plot data from csv for specific date and time using matplotlib?


Tag : python , By : fstender
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Retrieve Variable From Class
  • What is the reason for matplotlib for printing labels multiple times?
  • Why would people use ThreadPoolExecutor instead of direct function call?
  • When clear_widgets is called, it doesnt remove screens in ScreenManager
  • Python can't import function
  • Pieces doesn't stack after one loop on my connect4
  • How to change font size of all .docx document with python-docx
  • How to store a word with # in .cfg file
  • How to append dictionaries to a dictionary?
  • How can I scrape text within paragraph tag with some other tags then within the paragraph text?
  • Custom entity ruler with SpaCy did not return a match
  • Logging with two handlers - one to file and one to stderr
  • How to do pivot_table in dask with aggfunc 'min'?
  • This for loop displays only the last entry of the student record
  • How to split a string by a specific pattern in number of characters?
  • Python 3: how to scrape research results from a website using CSFR?
  • Setting the scoring parameter of RandomizedSeachCV to r2
  • How to send alert or message from view.py to template?
  • How to add qml ScatterSeries to existing qml defined ChartView?
  • Django + tox: Apps aren't loaded yet
  • My css and images arent showing in django
  • Probability mass function sum 2 dice roll?
  • Cannot call ubuntu 'ulimit' from python subprocess without using shell option
  • Dataframe Timestamp Filter for new/repeating value
  • Problem with clicking select2 dropdownlist in selenium
  • pandas dataframe masks to write values into new column
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com