Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dates on graph
#11
Dear Yoriz,
as I mentioned in the other thread, this thread is only a subset of the one in the other section.
Kindly refer to the one in the general questions since is more complete, and I will detail the case there.
Reply
#12
This is why you don't create unnecessary duplicate threads, these threads are going to be merged please don't open a new one.
Reply
#13
Hi Yoriz,
this part of the code seems to be the problem"
y = [mov_index(position1, position1+10), mov_index(position2, position2+10), mov_index(position3, position3+10)]
x = [CEU_times[position1] + datetime.timedelta(days=i) for i in range(len(y))]
ax = plt.subplot(111)
ax.bar(x, y, width=5)
ax.xaxis_date()
 
plt.setp(ax.get_xticklabels(), rotation=45, fontsize=10)
plt.show()
If I try to change the width of the bar, that seems to change the format of the date I see on the graph.I want to be able to see year-month-date instead of month-date-hour, and I want the x-axis to be separated by hours (for a better Idea if what I mean, kindly refer to the link http://ctr.maths.lu.se/na/courses/NUMA01.../birds.pdf). So far, the only way for me to be able to see the dates in the right format, is to keep the width of the bars to a minimum of 5, which is too much if I want them to be separated and have a better picture. If I lower that 5, the date format in the graph immediately changes to month-day-hour.
Let me please know if additional info are needed.
Reply
#14
Ok great, now hard code the missing variables and add the missing required imports so this small snippet of code will run for others to execute it and see the results you are seeing.
Reply
#15
I am afraid that the whole code (the first one posted above) is needed.
Why can't you refer to/ run that?
If you do so, you will see the results I get.

The file I am using is too large to upload, so down here is a sample.
Let me please know if this is enough.
Again, if you run the first code I posted, it shouldn't be an issue for anyone
to see the results I am seeing.


here is the code that I am now running, and I am getting the outcome described before.

rom astral import Astral 
from scipy import *
from pylab import*
import numpy as np
from numpy import array
import matplotlib.pyplot as plt
import datetime
from datetime import timezone
from datetime import timedelta
import matplotlib.dates as dates
import pandas as pd  
import pytz
import sys

def last_digits(num, last_digits_count=2):
    return abs(num) % (10**last_digits_count)

orig_date=[]
orig_time=[]
movements=[]

with open('bird_jan25jan16.txt', 'r') as f:
    for line in f:
        data = line.split()    # Splits on whitespace        
        orig_date.append(data[0][:])
        orig_time.append((data[1][:]))
        movements.append(int(data[2][:]))
    for i in range(0,len(orig_date)):
        if ((len(str(movements[i-1])) - len(str(movements[1]))) >=2):            
            if movements[i]==0 or (  (movements[i-1] == movements[i+1] ) and  (last_digits(movements[i-1]) == last_digits(movements[i]))):
                movements[i]=((movements[i-1]+movements[i+1])/2)
            


""" putting date and time together and converting them to datetime objects"""

dt_fmt = '%Y-%m-%d %H:%M:%S.%f'


timestamps = []


for col_dt in zip(orig_date , orig_time):
    
    new_dt_str = ' '.join(col_dt)
    new_dt = datetime.datetime.strptime(new_dt_str, dt_fmt)
    timestamps.append(new_dt)
    



def convert_local_timezone():
    converted_dates=[]
    for date in timestamps:
        local_tz = pytz.timezone('Europe/Berlin')
        local_time = date.replace(tzinfo=pytz.utc).astimezone(local_tz)
        converted_dates.append(local_time)
    return converted_dates

CEU_times=convert_local_timezone()



def mov_index(i,j):
    return sum(movements[i:j])


#x = pd.Timestamp('2015-01-25')
#res = next((i for i, j in enumerate(CEU_times[0:5]) if j == x),10)
#print(res)
#print(CEU_times[0].year , CEU_times[0].month , CEU_times[0].day)
position1 =  orig_date.index(("2015-01-25"))
position2 = orig_date.index('2015-01-26')
position3 = orig_date.index('2015-01-27')


from matplotlib.dates import date2num
print(type(CEU_times[0]))
print(CEU_times[position1].date()) # it correctly prints the date


city_name = 'Berlin'
a = Astral()
a.solar_depression = 'civil'
city = a[city_name]



y = [mov_index(position1, position1+10), mov_index(position2, position2+10), mov_index(position3, position3+10)]
x = [CEU_times[position1] + datetime.timedelta(days=i) for i in range(len(y))]
sun1 = (city.sun(date=(CEU_times[position1]), local=True   ))

ax = plt.subplot(111)
ax.bar(x, y, width=5) # by lowering the width the dates will have the format (month, day, hour)
ax.xaxis_date()

print('Dawn:    %s' % str(sun1['dawn']))
print('Sunset:  %s' % str(sun1['sunset']))

plt.setp(ax.get_xticklabels(), rotation=45, fontsize=10)
plt.show()

doesn't anyone know the answer or more info are needed?
Reply
#16
I cant run the code because i don't have astral.
I want to be able to help with the least effort on my part possible.
I would rather not create a text file and install modules just to make code run that's unrelated to the problem.
If you are happy with the code up to the point of it being plotted its not part of the problem.

just before x and y are plotted they have been assigned values from all the previous code,
print out x and y and hard code a sample of it that will show the problem into the following code.
import matplotlib.pyplot as plt

y = []  # contents of the list at this point
x = []  # contents of the list at this point

ax = plt.subplot(111)
ax.bar(
    x, y, width=5
)  # by lowering the width the dates will have the format (month, day, hour)
ax.xaxis_date()

plt.setp(ax.get_xticklabels(), rotation=45, fontsize=10)
plt.show()
now all i have to do to see the same result as you is copy and paste these few lines, i only need to have matplotlib installed, i don't have to mess around with files unnecessarily.

Be aware that even after this, if i can run the code, it doesn't mean i will necessarily have a solution for you, but the easier you make it for everyone to try and help you the more likely you will get responses to the thread.
Reply
#17
Dear Yoriz,
thanks for your attempt.

A few things I would like to specify:

1- you are right when you say that I am happy with the code up to when I plot it.
2- you don't need astral in order to help me solve this issue, as I didn't include the sunrise time
in my graph yet.
3-I would like to enhance that the main issue that I have with the plot right now, is being able to slim the width of the bars without losing the date format on the graph, meanwhile, showing all the hours marked with small vertical lines. The link I included before will show you the graph that I am trying to obtain.
Let me please know if there is anything else that I should provide.

for the values of y, I am currently trying these three:
700 760 980

and for x, these 3 dates:

2015-01-25, 2015-01-26, 2015-01-27
Reply
#18
You've got to continue playing with this to try and get what you want

I used these references
https://matplotlib.org/gallery/text_labe...ns-date-py
https://matplotlib.org/gallery/ticks_and..._demo.html

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import AutoMinorLocator
import datetime


years_fmt = mdates.DateFormatter('%Y-%m')
hour = mdates.HourLocator()
hours_fmt = mdates.DateFormatter('%H')

dates = ["2015-01-25", "2015-01-26", "2015-01-27"]
y = [700, 760, 980]  # contents of the list at this point
x = [
    datetime.datetime.strptime(date, '%Y-%m-%d').date() for date in dates
]  # contents of the list at this point

ax = plt.subplot(111)
ax.bar(
    x, y, width=5
)  # by lowering the width the dates will have the format (month, day, hour)
ax.xaxis_date()

# format the ticks

ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_minor_locator(hour)
ax.xaxis.set_minor_formatter(hours_fmt)
ax.xaxis.set_minor_locator(AutoMinorLocator(8))


plt.setp(ax.get_xticklabels(), rotation=45, fontsize=10)
plt.show()
Reply
#19
Can you simplify your question to 5-10 lines of code, no imports, and your file hard-coded into the script? I tend to skip questions that are too much code, and in your cases it's definitely more imports than are needed to reproduce the issue.
Reply
#20
Until mcgrim can ask simplified questions that don't rely on all this code that's irrelevant to the question, i'm merging any threads into this one.

Note: micseydel's post previous to this, is in reply to the the posts by mcgrim that after merging are the first two posts of this thread.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020